标签:
某个View的显示流程是这样的:
Activity.onCreate-->Activity.onStart-->Activity.onResume-->image.onMeasure-->image.onLayout-->onGlobalLayoutListener-->Activity.onWindowFocusChanged-->....-->image.onDraw
onWindowFocusChanged是当activity可见时的调用的,在此之前的函数中调用View.getWidth/getHeight得到的是0,onWindowFocusChanged函数中获View.getWidth/getHeight是合适的。getWidth/getHeight一般是控件添加到Activity之后,显示到屏幕中的实际宽度。而View.getMeasureWidth/getMeasureHeight是配合view.measure使用的,如果未调用View.measure,那么调用view.getMeasureWidth的效果和View.getWidth一样。
如果我们要在onWindowFocusChanged之前的函数,如onCreate中获得View的宽度/高度,有如下三种方法:
方法一:
int width =View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED); int height =View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED); view.measure(width,height); int height=view.getMeasuredHeight(); int width=view.getMeasuredWidth();
ViewTreeObserver vto =view.getViewTreeObserver(); vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { int height =view.getMeasuredHeight(); int width =view.getMeasuredWidth(); } });
ViewTreeObserver vto = view.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){ @Override public void onGlobalLayout() { view.getViewTreeObserver().removeGlobalOnLayoutListener(this); int height =view.getMeasuredHeight(); int width =view.getMeasuredWidth(); } });
View的getWidth/getHeight与getMeasuredWidth/getMeasuredHeight的区别
标签:
原文地址:http://blog.csdn.net/u010852801/article/details/45670571