您的位置:首页 > 其它

View的onMeasure方法

2016-04-18 17:44 260 查看
View.MeasureSpec类中的常量:

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


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

int specMode = MeasureSpec.getMode(measureSpec);//UNSPECIFIED,EXACTLY,AT_MOST
int 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
}
@Override
public 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>


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: