码迷,mamicode.com
首页 > 其他好文 > 详细

View的getWidth/getHeight与getMeasuredWidth/getMeasuredHeight的区别

时间:2015-05-12 17:17:20      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

某个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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!