Gif中意思是蓝色控件将红色控件挤出父容器了, 要求是不让红色控件被挤出父容器而蓝色控件也能自由的向下扩展.
- 两个View水平,父容器选择
LinearLayout . - 两个View宽度相加, 小于父容器宽度, 就不做处理. 效果和
LinearLayout 里一样. - 两个View相加宽度大于父容器宽度, 就要重新计算子View的宽度和高度了.下面是具体代码:
public class HotNewsItemView extends LinearLayout {
public HotNewsItemView(Context context) {
this(context, null);
}
public HotNewsItemView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public HotNewsItemView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int mParentWidthSize = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight();
View mContentView = getChildAt(0);
View mHotTageView = getChildAt(1);
measureChild(mContentView, widthMeasureSpec, heightMeasureSpec);
measureChild(mHotTageView, widthMeasureSpec, heightMeasureSpec);
MarginLayoutParams mContentViewMLP = (MarginLayoutParams) mContentView.getLayoutParams();
int mContentViewWidth = mContentView.getMeasuredWidth() + mContentViewMLP.leftMargin + mContentViewMLP.rightMargin;
MarginLayoutParams mHotTageViewMLP = (MarginLayoutParams) mHotTageView.getLayoutParams();
int mHotTageViewWidth = mHotTageView.getMeasuredWidth() + mHotTageViewMLP.leftMargin + mHotTageViewMLP.rightMargin;
if (mContentViewWidth + mHotTageViewWidth >= mParentWidthSize) {
int newContentViewhMS = MeasureSpec.makeMeasureSpec(mParentWidthSize - mHotTageViewWidth, MeasureSpec.EXACTLY);
measureChild(mContentView, newContentViewhMS, heightMeasureSpec);
MarginLayoutParams mAgainContentViewMLP = (MarginLayoutParams) mContentView.getLayoutParams();
int mContentViewHeight1 = mContentView.getMeasuredHeight() + mAgainContentViewMLP.topMargin + mAgainContentViewMLP.bottomMargin;
setMeasuredDimension(mParentWidthSize, mContentViewHeight1);
}
}
}
<com.example.myapplication.HotNewsItemView
android:background="@android:color/darker_gray"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="4dp"
android:text="冷"
android:textColor="@color/colorAccent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="4dp"
android:text="热"
android:textColor="@color/read" />
</com.example.myapplication.HotNewsItemView>
measureChild(mContentView, widthMeasureSpec, heightMeasureSpec); 根据父容器测量规格测量子View宽高getMeasuredWidth() 子View测量后获取子View宽度setMeasuredDimension(mParentWidthSize, mContentViewHeight1) 设置父容器的宽高值
- 最终效果图
|