您的位置:首页 > 移动开发 > Android开发

android 自定义控件学习

2016-03-25 22:56 417 查看
View测量:
系统提供了一个强大的类---MeasureSpec类通过它来帮助我们测量View
MeasureSpec是一个32位的int值,其中高2位为测量模式,低30位为测量的大小

测量模式为以下三种:
EXACTLY:
即精准模式,当我们将控件的layout_width属性或者layout_height属性制定为具体数值时,比如100dp
或者为match_parent属性(占据父View大小)系统使用的是EXACTLY模式

AT_MOST:
即最大值模式,当控件的layout_width属性或者layout_height属性制定为wrap_centent时,控件一般随着子控件的大小
的内容变化而变化,此时控件的尺寸只要不超过父控件的允许尺寸即可

UNSPECIFIED:
View想多大就多大

View类默认的模式为EXACTLY模式,如果自定义控件不复写onMeasure()方法就只能使用EXACTLY模式
如果让自定义View支持wrap_centent属性必须重写onMeasure()方法

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(measuredWidth(widthMeasureSpec), measureHeight(heightMeasureSpec));
}

private int measuredWidth(int widthMeasureSpec) {
//1.从MeasureSpec类中具体的测量模式和大小
int specMode = MeasureSpec.getMode(widthMeasureSpec);
int specSize = MeasureSpec.getSize(widthMeasureSpec);
//通过判断测量模式给出不同的值,当specMode为EXACTLY时直接使用制定的specMode;当为
//其他两种模式时需要给一个默认的大小如果指定的wrap_centent属性,即AT_MOST,则需要取出我们指定的大小
//与specSize中最小的一个来作为测量
int result = 0;
if(specMode == MeasureSpec.EXACTLY){
result = specSize;
}else{
result = 200;
if(specMode == MeasureSpec.AT_MOST){
result = Math.min(result,specSize);
}
}
return result;
}

private int measureHeight(int heightMeasureSpec) {
int specMode = MeasureSpec.getMode(heightMeasureSpec);
int specSize = MeasureSpec.getSize(heightMeasureSpec);

int result = 0;
if(specMode == MeasureSpec.EXACTLY){
result = specSize;
}else{
result = 200;
if(specMode == MeasureSpec.AT_MOST){
result = Math.min(result,specSize);
}
}
return result;
}

@Override
protected void onFinishInflate() {//从XML加载组件后调用
super.onFinishInflate();
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {//当组件大小改变时回掉
super.onSizeChanged(w, h, oldw, oldh);
}

@Override//回调该方法来确定显示位置
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
}

@Override//监听触摸事件回调
public boolean onTouchEvent(MotionEvent event) {
return super.onTouchEvent(event);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: