我已经创建了一个自定义视图,并尝试实现onMeasure()以便在所有情况下都能很好地工作。我现在想知道当我的视图放在一个线性布局中时,作为width/heightMeasurementSpec传递的参数是什么:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<MyView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/someId"></MyView>
</LinearLayout>在这种情况下,
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int height = MeasureSpec.getSize(heightMeasureSpec);
int heightmode = MeasureSpec.getMode(heightMeasureSpec);
//...
}我的height = 271 (在480x320屏幕上)和heightmode = AT_MOST,这似乎很有意义。
但是当我在我的视图之后添加一些这样的TextViews时:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<MyView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/someId"></MyView>
<TextView android:text="1" android:layout_width="fill_parent"
android:layout_height="wrap_content"></TextView>
<TextView android:text="2" android:layout_width="fill_parent"
android:layout_height="wrap_content"></TextView>
</LinearLayout>我仍然得到相同的height/heightmode值(onMeasure实际上被调用了两次,但使用了相同的参数)。我想,当TextViews消耗一些空间时,MyView的空间应该会更小吗?(这是可以的,但我需要知道我可以占用多少空间……)
有什么想法吗?非常感谢!
发布于 2011-01-17 13:58:31
我想出了如何实现我想要的:
1.)决定是否应该填满所有可用的空间不是视图的责任。这是在布局中完成的。
2.)我可以通过如下所示的布局为我的视图提供所有剩余的垂直空间
<MyView
android:layout_width="fill_parent"
android:layout_height="0px" android:layout_weight="1"></MyView>3.)onMeasure()应该通过考虑模式(getMode(widthMeasurementSpec))来设置测量的尺寸。
发布于 2011-01-16 16:14:21
您可以在自定义视图之后添加TextViews,因此它们的高度不会影响自定义视图的高度。
https://stackoverflow.com/questions/4704205
复制相似问题