Andriod自定义View三:getWidth()与getMeasuredWidth()的区别

自定义控件的时候getMeasuredWidth/getMeasuredHeight它的赋值在View的setMeasuredDimension中,所以有时可以在onMeasure方法中看到利用getMeasuredWidth/getMeasuredHeight初始化别的参数。而getWidth/getHeight一直在onLayout完成后才会被赋值。一般情况下,如果都完成了赋值,两者值是相同的。

可以在自定义View的onMessure、onLayout、onDraw里面打印看看区别

public class MyView extends View {


    private static final String TAG = MyView.class.getSimpleName();

    public MyView(Context context) {
        super(context);
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        Log.d(TAG, "======>"+"onMeasure") ;
        printWH();
    }

    private void printWH() {
        Log.d(TAG,"getMeasuredWidth:"+getMeasuredWidth());
        Log.d(TAG,"getMeasuredHeight:"+getMeasuredHeight());
        Log.d(TAG,"getWidth:"+getWidth());
        Log.d(TAG,"getHeight:"+getHeight());
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        Log.d(TAG,"======>"+"onLayout") ;
        printWH();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.d(TAG,"======>"+"onDraw") ;
        printWH();
    }
}
Andriod自定义View三:getWidth()与getMeasuredWidth()的区别_第1张图片
Paste_Image.png

本文作者地址:
http://www.jianshu.com/u/303ec9abdc08
作者博客地址:http://blog.csdn.net/e_Inch_Photo/article/details/61190342

你可能感兴趣的:(Andriod自定义View三:getWidth()与getMeasuredWidth()的区别)