Linearlayout横向布局两个textview,优先显示后面textview,前面textview省略显示

在项目中有事需要在Linearlayout横向布局中有两个textview情况下,优先后面view完全显示,当不能完全显示是前面的textview省略显示,但android自带的Linearlayout不能满足需求,总是优先显示前面的view,所以针对这种情况对Linearlayout做了自定义封装
重写onMeasure方法,重新测量子view控制优先显示后面的子view

自定义Linearlayout

public class XLinearlayout extends LinearLayout {

    private int rest;
    int mLeft, mRight, mTop, mBottom;

    public XLinearlayout(Context context) {
        this(context, null);
    }


    public XLinearlayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //非横排和不开启RearFirst,则用系统默认measure
        if (!isHorizon()) {
            return;
        }
        int mWidth  = MeasureSpec.getSize(widthMeasureSpec);//可用宽度
        int mHeight = getMeasuredHeight();
        int mCount  = getChildCount();//子view数量
        //计算预计总宽
        int preComputeWidth = 0;
        //临时记录位置
        mLeft = 0;
        mRight = 0;
        mTop = 0;
        mBottom = 0;

        rest = mWidth;

        for (int i = mCount - 1; i >= 0; i--) {//从后往前算(因为要顺便计算position以备使用)
            final View child = getChildAt(i);
            int        spec  = MeasureSpec.makeMeasureSpec(rest, MeasureSpec.AT_MOST);
            child.measure(spec, MeasureSpec.UNSPECIFIED);
            int childw = child.getMeasuredWidth();
            int childh = child.getMeasuredHeight();
            preComputeWidth += childw;

            //计算rest
            mRight = getPositionRight(i, mCount, mWidth);
            mLeft = mRight - childw;
            mBottom = mTop + childh;
            rest = mLeft;
        }
        //保存最终的测量结果
        if (preComputeWidth <= mWidth) {
            setMeasuredDimension(preComputeWidth, mHeight);
        } else {
            setMeasuredDimension(mWidth, mHeight);
        }
    }

    private boolean isHorizon() {
        return getOrientation() == HORIZONTAL;
    }

    public int getPositionRight(int index, int count, int totalWidth) {
        if (index < count - 1) {
            return getPositionRight(index + 1, count, totalWidth) - getChildAt(index + 1).getMeasuredWidth();
        }
        return totalWidth - getPaddingRight();
 

布局中调用

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

            android:id="@+id/tv_textview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:lines="1"
        android:text="迷糊一二三四五六七八九十"
        android:textSize="16sp" />
            android:id="@+id/tv_textview2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:lines="1"
        android:text="一二三四五六七八九十1234567890"
        android:textSize="13sp" />

 

你可能感兴趣的:(android)