onmeasure方法
View的最终大小在这个方法中测量完成,其中由
setMeasuredDimension(100,100);
完成。
测量有三种模式
*EXACTLY ------精确值模式
当我们在布局中将宽高设置成精确的dp或为match_partent,系统指定为EXACTLY模式 。
*AT MOST -------最大值模式
当我在磨具中将宽高设置成wrap_content时,控件大小随着子控件大小或内容的变化而变化,只要不超过父控件允许的最大尺寸。
*UNSPECIFIED----不指定大小测量模式
不指定view大小,view想要多大就给多大,通常只有在自定义View使用该模式。
系统默认使用EXACTLY模式,如果不重写onmeasure只能在布局中使用精确的dp或match_partent,如果要让自定义view支持wrap_content,必须重写onmeasure方法来指定大小。通过这个方法我们能获得view测量模式和大小,从而控制view最后显示的大小。实例如下:
private int measureWidth(int measureSpec) {
int result = 0;
//第一步:从measureSpec对象中提取出具体的测量模式和大小
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
//第二步:通过判断测量的模式,给出不同的测量值。
//当specMode为EXACTLY时,直接指定的specSize即可,
//当specMode为其他模式时,需要给它一个默认的大小
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else {
result = 200;
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
onlayout(int l,int t,int r,int b)方法 左 上 右 下
各个view具体位置在这个方法中进行布置
//测量各个子view大小 measureChildren(widthMeasureSpec, heightMeasureSpec);
@Override protected void onLayout(boolean changed, int l, int t, int r, int b) { // 获得子View个数 int childCount = getChildCount(); // 设置一个变量保存到父View左侧的距离 int mLeft = 0; // 遍历子View for (int i = 0; i < childCount; i++) { View childView = getChildAt(i); // 获得子View的高度 int childViewHeight = childView.getMeasuredHeight(); // 获得子View的宽度 int childViewWidth = childView.getMeasuredWidth(); // 让子View在竖直方向上显示在屏幕的中间位置 int height = sreenH / 2 - childViewHeight / 2; // 调用layout给每一个子View设定位置mLeft,mTop,mRight,mBottom.左上右下 childView.layout(mLeft, height, mLeft + childViewWidth, height + childViewHeight); // 改变下一个子View到父View左侧的距离 mLeft += childViewWidth; } }
自定义属性
第一步
在资源文件:resources/attr并在其中定义自己需要的属性
<declare-styleable name="test">
<attr name="test" format="string" />
<attr name="testArr" format="integer" />
</declare-styleable>
第二步
自定义view类获取自定义view属性
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.test);
String text = ta.getString(R.styleable.test_testArr);
int textAttr = ta.getInteger(R.styleable.test_text, -1);
Log.e(TAG, "text:"+text+",textAttr:"+textAttr);
ta.recycle();
}
第三步
在布局文件中使用
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:yxm="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="org.xm.customview.MainActivity">
<org.xm.customview.MyTextView
android:layout_width="100dp"
android:layout_height="200dp"
yxm:testArr="20"
yxm:text="xiaoming" />
</RelativeLayout>
注意:androidstudio中使用:xmlns:yxm="http://schemas.android.com/apk/res-auto"
自动导入命名控件。给自定义属性添加参数使用制定定义的命名空间,例如: yxm:testArr="20"。