美文网首页
Activity中获取view的高度和宽度为0的原因以及解决方案

Activity中获取view的高度和宽度为0的原因以及解决方案

作者: Nj_第一批老去的90后 | 来源:发表于2017-03-24 10:38 被阅读152次

现象

在activity中可以调用View.getWidth、View.getHeight()、View.getMeasuredWidth() 、View.getgetMeasuredHeight()来获得某个view的宽度或高度,但是在onCreate()、onStrart()、onResume()方法中会返回0

原因

当前activity所代表的界面还没显示出来没有添加到WindowPhone的DecorView上或要获取的view没有被添加到DecorView上或者该View的visibility属性为gone 或者该view的width或height真的为0  所以只有上述条件都不成立时才能得到非0的width和height  

解决方案

  • 在activity被显示出来时即添加到了DecorView上时获取宽和高如onWindowFocusChanged() 回调方法
@Override  
  public void onWindowFocusChanged(boolean hasFocus) {  
      View iv1 = findViewById(R.id.iv1);  
      View iv2=findViewById(R.id.iv2);  
      String msg1="iv1' width:"+iv1.getWidth()+"            height:"+iv1.getHeight()+"   measuredWidth:"+iv1.getMeasuredWidth()+"measuredHeight:"+iv1.getMeasuredHeight();  
   String msg2="iv2' width:"+iv2.getWidth()+"   height:"+iv2.getHeight()+"  measuredWidth:"+iv2.getMeasuredWidth()+"measuredHeight:"+iv 2.getMeasuredHeight();  
i("onWindowFocusChanged() "+msg1);  
i("onWindowFocusChanged() "+msg2);  
    super.onWindowFocusChanged(hasFocus);  
  } 

相关文章

网友评论

      本文标题:Activity中获取view的高度和宽度为0的原因以及解决方案

      本文链接:https://www.haomeiwen.com/subject/ejwxottx.html