<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/root" android:layout_width="match_parent" android:layout_height="wrap_content" tools:context=".MainActivity" > <!-- 控件1 --> <FrameLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <com.example.test.MeasTestLayout android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="haole" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="hsb" /> </com.example.test.MeasTestLayout> </FrameLayout> <!- 控件2 -> <FrameLayout android:layout_width="match_parent" android:layout_height="100dp" > <com.example.test.MeasTestLayout android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="haole" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="hsb" /> </com.example.test.MeasTestLayout> </FrameLayout>
<!- 控件3 -> <FrameLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <com.example.test.MeasTestLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="haole" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="hsb" /> </com.example.test.MeasTestLayout> </FrameLayout> <!- 控件4 -> <FrameLayout android:layout_width="match_parent" android:layout_height="100dp" > <com.example.test.MeasTestLayout android:layout_width="match_parent" android:layout_height="50dp" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="haole" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="hsb" /> </com.example.test.MeasTestLayout> </FrameLayout> </FrameLayout>
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // TODO Auto-generated method stub super.onMeasure(widthMeasureSpec, heightMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); log("widthMode: "+ widthMode +" heightMode: "+heightMode); print(widthMode); print(heightMode); }
结果:
控件1:EXACTLY AT_MOST
控件2:EXACTLY EXACTLY
控件3:EXACTLY AT_MOST
控件4:EXACTLY EXACTLY
结论:1、自定义控件中的onMeasure方法接收的参数的Mode与它的父控件的w、h有关,与它自身的宽高无关
2、如果父控件的高度是wrap_content 则接收到的参数mode为AT_MOST,表示最大高度是传入值
3、如果父控件的高度是match_parent 或者 固定的dp值,则接收到的参数的mode为EXACTLY,表示高度已经是确定值。
原文:http://www.cnblogs.com/lipeil/p/4968477.html