您的位置:首页 > 其它

自定义View-2-重写onMeasure

2016-04-23 11:19 302 查看

效果图



布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#003839"
android:gravity="center"
android:visibility="visible"
android:text="SECOND"/>

<com.pengkv.apple.weight.FirstView
android:layout_width="wrap_content"
android:visibility="visible"
android:background="#888787"
android:layout_height="wrap_content"/>

</LinearLayout>


View代码

public class FirstView extends LinearLayout {

public FirstView(Context context) {//代码实例化的时候调用
super(context);
}

public FirstView(Context context, AttributeSet attrs) {//布局文件引用的时候调用
super(context, attrs);
}

public FirstView(Context context, AttributeSet attrs, int defStyleAttr) {//自定义属性值的时候调用
super(context, attrs, defStyleAttr);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        super.onMeasure(widthMeasureSpec,heightMeasureSpec);
setMeasuredDimension(measureSpec(widthMeasureSpec),measureSpec(heightMeasureSpec)); //重测尺寸
}

public int measureSpec(int measureSpec){
int result=0;
int specMode=MeasureSpec.getMode(measureSpec);//获取测量模式
int specSize=MeasureSpec.getSize(measureSpec);//获取测量尺寸

if (specMode==MeasureSpec.EXACTLY){//精确模式:包括准确设置dp值和match_parent
result=specSize;
}else {
result=400;//默认设置的尺寸
if (specMode==MeasureSpec.AT_MOST){
result=Math.min(result,specSize);
}
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: