获取Android控件的宽和高

 我们都知道在onCreate()里面获取控件的高度是0,这是为什么呢?我们来看一下示例:
public class MyImageView extends ImageView {
    public MyImageView(Context context, AttributeSet attrs) { 
        super(context, attrs); 
    } 
    public MyImageView(Context context) { 
        super(context); 
    }
    @Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
        super.onMeasure(widthMeasureSpec, heightMeasureSpec); 
        System.out.println("onMeasure 我被调用了"+System.currentTimeMillis()); 
    }
    @Override 
    protected void onDraw(Canvas canvas) { 
        super.onDraw(canvas); 
        System.out.println("onDraw 我被调用了"+System.currentTimeMillis()); 
    }

布局文件:
<com.test.MyImageView 
    android:id="@+id/imageview" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:src="@drawable/icon" /> 

测试的Activity的onCreate():
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main);         
    System.out.println("执行完毕.."+System.currentTimeMillis()); 
}

      等onCreate方法执行完了,我们定义的控件才会被度量(measure),所以我们在onCreate方法里面通过 view.getHeight()获取控件的高度或者宽度肯定是0,因为它自己还没有被度量,也就是说他自己都不知道自己有多高,而你这时候去获取它的尺 寸,肯定是不行的。解决方法如下:

方法一:

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(); 
textView.append("\n"+height+","+width);

方法二:

ViewTreeObserver vto = imageView.getViewTreeObserver(); 
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { 
    public boolean onPreDraw() { 
        int height = imageView.getMeasuredHeight(); 
        int width = imageView.getMeasuredWidth(); 
        textView.append("\n"+height+","+width); 
        return true; 
    } 
});

方法三:

ViewTreeObserver vto2 = imageView.getViewTreeObserver();   
vto2.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    @Override   
    public void onGlobalLayout() { 
        imageView.getViewTreeObserver().removeGlobalOnLayoutListener(this);   
        textView.append("\n\n"+imageView.getHeight()+","+imageView.getWidth()); 
    }   
});

原文地址:https://www.cnblogs.com/zhongle/p/2769951.html