View的onMeasure方法

来源:互联网 发布:python 私有属性 知乎 编辑:程序博客网 时间:2024/06/09 23:49
View.MeasureSpec类中的常量:

private static final int MODE_SHIFT = 30;public static final int UNSPECIFIED = 0 << MODE_SHIFT;//0public static final int EXACTLY     = 1 << MODE_SHIFT;//1073741824public static final int AT_MOST     = 2 << MODE_SHIFT;//-2147483648

由onMeasure方法带的参数widthMeasureSpec、heightMeasureSpec,得到View的尺寸的规格和大小:

int specMode = MeasureSpec.getMode(measureSpec);//UNSPECIFIED,EXACTLY,AT_MOSTint specSize = MeasureSpec.getSize(measureSpec);

实例代码

public class TestView extends View {public TestView(Context context, AttributeSet attrs) {super(context, attrs);// TODO Auto-generated constructor stub}public TestView(Context context) {super(context);// TODO Auto-generated constructor stub}@Overridepublic void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {Log.v("view.onMeasure", "widthMeasureSpec="+widthMeasureSpec);Log.v("view.onMeasure", "heightMeasureSpec="+heightMeasureSpec);int widthMode = MeasureSpec.getMode(widthMeasureSpec);int heightMode = MeasureSpec.getMode(heightMeasureSpec);int widthSize = MeasureSpec.getSize(widthMeasureSpec);int heightSize = MeasureSpec.getSize(heightMeasureSpec);Log.v("view.onMeasure", "widthMode="+widthMode);Log.v("view.onMeasure", "heightMode="+heightMode);Log.v("view.onMeasure", "widthSize="+widthSize);Log.v("view.onMeasure", "heightSize="+heightSize);super.onMeasure(widthMeasureSpec, heightMeasureSpec);}}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.example.viewlearning.MainActivity" >    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world" /><com.example.viewlearning.TestView     android:layout_width="50dp"    android:layout_height="50dp"    android:background="#666666"/></LinearLayout>


0 0
原创粉丝点击