具有高度wrap_content和子match_parent的PercentRelativeLayout

时间:2016-02-17 15:40:47

标签: android layout percentage

  1. 我正在使用内部有多个子项的PercentRelativeLayout
  2. 我希望有些孩子的身高与父母一样
  3. 父母的身高应为“wrap_content”
  4. 这是一个过于简单的例子,不起作用:

    <android.support.percent.PercentRelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/red"
        >
        <TextView
            android:id="@+id/text1"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="Label1 \n Line2 \n Line3"
            android:background="@color/green"
            />
    
        <TextView
            android:id="@+id/text2"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:background="@color/blue"
            android:layout_alignParentRight="true"
            android:text="Label2 with\n two lines"/>
    </android.support.percent.PercentRelativeLayout>
    

    解决此问题的最简单方法是什么?

1 个答案:

答案 0 :(得分:0)

作为一种解决方法,我做了以下操作,请评论是否可以这样做(更改onMeasure中的儿童身高)

public class PercentageRelativeLayout extends PercentRelativeLayout
{
public PercentageRelativeLayout(Context context) {
    super(context);
}

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

public PercentageRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if(getLayoutParams().height == LayoutParams.WRAP_CONTENT) {
        ArrayList<ViewGroup.LayoutParams> modifiedLayouts = new ArrayList<>();
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            if (child.getLayoutParams().height == LayoutParams.MATCH_PARENT) {
                child.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
                modifiedLayouts.add(child.getLayoutParams());
            }
        }

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        if(modifiedLayouts.size() > 0) {
             int heightHint = getMeasuredHeight();

            if(heightHint > 0) {
                getLayoutParams().height = heightHint;
            }

            for (ViewGroup.LayoutParams params : modifiedLayouts)
                params.height = LayoutParams.MATCH_PARENT;

            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            return;
        }
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}