获取Android控件的真实宽高,亲测有效

//方法1
int w = View.MeasureSpec.makeMeasureSpec(0,
        View.MeasureSpec.UNSPECIFIED);
int h = View.MeasureSpec.makeMeasureSpec(0,
        View.MeasureSpec.UNSPECIFIED);
imageView.measure(w, h);
int height = imageView.getMeasuredHeight();

int width = imageView.getMeasuredWidth();

---------------------------------------------------------------------

//方法2
ViewTreeObserver vto = imageView.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
    public boolean onPreDraw() {
        vto.removeOnPreDrawListener(this);
        int height = imageView.getMeasuredHeight();
        int width = imageView.getMeasuredWidth();
        return true;
    }
});
--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---

//方法3
ViewTreeObserver vto = imageView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        imageView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        imageView.getHeight();
        imageView.getWidth();
    }
});


你可能感兴趣的:(获取Android控件的真实宽高,亲测有效)