自定义View-2-重写onMeasure

效果图

这里写图片描述

布局文件

<?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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

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;
    }
}
posted @ 2017-04-22 18:22  天涯海角路  阅读(100)  评论(0)    收藏  举报