一、简单背景介绍
在自定义view(不是ViewGroup)时,需要重写父类的onMeausre(), onLayout(), onDraw():
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
看了很多书和文章,都介绍了widthMeasureSpec是什么东西。他是一个MeasureSpec
,32位的int,前两位记录了他的mode,后30位记录了他的size。
mode如下:
Mode | Name | Cool |
---|---|---|
00 | UNSPECIFIED | 0 |
01 | EXACTLY | 1073741824 |
10 | AT_MOST | -2147483648 |
但是widthMeasureSpec和heightMeasureSpec是从哪儿来的?他的mode和size是在xml中定义的mode和size?还是他父亲的mode和size?
二、探索onMeasure中的widthMeasureSpec
自定义view的xml文件如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.wangxuan.customviewheight.CustomView
android:layout_width="300px"
android:layout_height="400px"