Android wrap_内容不适用于自定义RelativeLayout
我创建了一个自定义布局,它扩展了Android wrap_内容不适用于自定义RelativeLayout,android,android-layout,Android,Android Layout,我创建了一个自定义布局,它扩展了RelativeLayout。目前,这个布局除了覆盖onMeasure方法(稍后我将需要该方法)之外,什么都不做。这是我的密码: public class CustomLayout extends RelativeLayout { public CustomLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override
RelativeLayout
。目前,这个布局除了覆盖onMeasure
方法(稍后我将需要该方法)之外,什么都不做。这是我的密码:
public class CustomLayout extends RelativeLayout {
public CustomLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
}
}
我有以下布局文件:
<LinearLayout
android:id="@+id/containerLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:orientation="horizontal" >
<...CustomLayout
android:id="@+id/item"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="50"
android:background="#fff" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello"
android:textSize="20sp" />
</...CustomLayout>
<RelativeLayout
android:id="@+id/controls"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="50"
android:background="#0f0" >
</RelativeLayout>
</LinearLayout>
问题是高度为空。在调试过程中,我注意到如果我将CustomLayout
更改为RelativeLayout
,它就会工作
因此,很明显,问题来自我的
CustomLayout
,但我需要添加什么才能使wrap\u内容正常工作?我终于找到了问题所在。我改变这一点:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
}
为此:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
而且效果很好
解释
首先,下面这句话没用:
setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
但是为什么它会使视图的高度为空
事实上,我误解了onMeasure
方法的参数。它们是MeasureSpec
值。以下是谷歌对该对象的看法:
MeasureSpec封装了从父级传递的布局要求
给孩子。每个MeasureSpec表示对以下两个方面的要求:
宽度或高度。MeasureSpec由大小和模式组成。
有三种可能的模式:
未指定父项未对子项施加任何约束。信息技术
可以是它想要的任何尺寸。确切地说,父级已确定
孩子的确切尺寸。孩子将被给予这些限制
不管它想要多大。这孩子最多也能像你一样
大到指定的大小。度量方面是
实现为int以减少对象分配。这个班是
用于将元组打包并解包到int中
widthmasurespec
和heightMeasureSpec
值不仅仅是视图的宽度和高度。在这种情况下,将这些值传递给setMeasureDimension
是完全错误的,因为此方法实际上需要实际尺寸作为参数。尝试设置高度以匹配父对象,并让我知道发生了什么?相同,高度为空。同样,如果我将RelativeLayout
与match_parent
一起使用,它会起作用。为什么要调用setMeasuredDimension(widthMeasureSpec,heightMeasureSpec);并覆盖super.onMeasure()的结果?是的,我刚刚注意到了这一点。当我看到你的评论时,我正在回答我的问题。无论如何,谢谢你的帮助;)