获取控件的Width和Height
1.在onCreate()中想要获取控件宽高,我们会获取到为一个蛋(至于是鸭蛋还是什么蛋你自己去想)
但要想获取还是有方法的,首先需要据被一些关于View的知识,这里我要简单提一下,为以后好直 接明白。之所以在onCreate()中无法获得是应为View还没有onMeasure()和onDraw()。
相关知识点(http://blog.csdn.net/feiyang877647044/article/details/51480952)
而onResume()后才会调用到onMeasure()和onDraw()。
那么下面几种方法为间接获取法:
A.在Activity调用onWindowFocusChanged()时View完成了onDraw();
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
System.out.println("haha" + imageView.getWidth());
}
B.用onMeasure方法(View.MeasureSpec.UNSPECIFIED是指宽高测量规格)
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);
上面两种方法为调用方法实现,还有几种调用相关接口实现的(这里列举一种其它在相关知识点中)
相关知识点:http://blog.csdn.net/x1617044578/article/details/39668667
这是用视图树观察者(视图是以树状一样从最内层排布的)来监听控件尺寸。
C.ViewTreeObserver vto = imageView.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
int height = imageView.getHeight();
int width = imageView.getWidth();
if (vto.isAlive())
//这里注意要注销监听,因为可能会被多次触发。
vto.removeOnPreDrawListener(this);
Log.i("haha",""+width);
return true;
}
});
总结:进过一些简单的实验证明:用onWindowFocusChanged()和addOnPreDrawListener()所获得的宽高更精确。(思考:应该是因为这两个方法都是在将要调用onDraw()方法了,在最后的绘制了。)