开发者

onMeasure() parameters provided by LinearLayout

开发者 https://www.devze.com 2023-02-05 02:53 出处:网络
I have created a custom view and I try to implement onMeasure() to work well in all situations. I am currently wondering about the parameters that are passed aswidth/heightMeasurementSpec when my view

I have created a custom view and I try to implement onMeasure() to work well in all situations. I am currently wondering about the parameters that are passed as width/heightMeasurementSpec when my view is placed within a linear layout like this:

<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>

In this case after doing

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
  int height = MeasureSpec.getSize(heightMeasureSpec);
  int heightmode = MeasureSpec.getMode(heightMeasureSpec);
  //...
}

I have height = 271 (on a 480x320 screen) and heightmode = AT_MOST which seems to make sense.

But when I add some TextViews like this after my view:

  <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="f开发者_C百科ill_parent"
  android:layout_height="wrap_content"></TextView>
    </LinearLayout>

I still get the same height/heightmode values (onMeasure is actually called twice, but with the same arguments). I thought that as the TextViews consume some space, there should be less space for MyView? (Which would be ok, but I need to know how much space I can occupy...)

Any ideas? Thanks a lot!


You add the TextViews after your custom view, so their height won't impact your custom view's height.


I figured out how to achieve what I wanted:

1.) it's not the responsibility of the View to determine whether it should fill all available space or not. This is done in the layout.

2.) I can give all remaining vertical space to my View by having a layout like

 <MyView   
  android:layout_width="fill_parent"
  android:layout_height="0px" android:layout_weight="1"></MyView>

3.) onMeasure() should set the measured dimension by considering the mode (getMode(widthMeasurementSpec)).

0

精彩评论

暂无评论...
验证码 换一张
取 消