栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

4种Android获取View宽高的方式

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

4种Android获取View宽高的方式

有时我们会有基于这样的需求,当Activity创建时,需要获取某个View的宽高,然后进行相应的操作,但是我们在onCreate,onStart中获取View的大小,获取到的值都是0,只是由于View的绘制工程还未完成,和在onCreate中弹出Dialog或者PopupWindow会报一个Activity not running原理类似。

接下来就为大家介绍几种获取View宽高的方法:
第一种方式:重写Activity中的onWindowFocusChanged,当Activity获取到焦点的时候View已经绘制完成,也能获取到View的准确宽高了。同样的Dialog和PopupWindow也可以在这里弹出,需要注意的是这个方法会调用多次,当hasFocus为true时,才可进行相应的操作

@Override
  public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
      System.out.println("onWindowFocusChanged width="
   + tvTest.getWidth() + " height=" + tvTest.getHeight());
    }
  }

第二种方式:


  private void getSize1() {

    ViewTreeObserver vto = tvTest.getViewTreeObserver();
    vto.addonPreDrawListener(new ViewTreeObserver.onPreDrawListener() {
      @Override
      public boolean onPreDraw() {
 int height = tvTest.getMeasuredHeight();
 int width = tvTest.getMeasuredWidth();
 System.out.println("height" + height);
 System.out.println("width" + width);
 return true;
      }

    });
  }

第三种方式:

private void getSize2() {
    ViewTreeObserver viewTreeObserver = tvTest.getViewTreeObserver();
    viewTreeObserver
 .addonGlobalLayoutListener(new onGlobalLayoutListener() {
   @Override
   public void onGlobalLayout() {
     tvTest.getViewTreeObserver()
  .removeGlobalonLayoutListener(this);
     System.out.println("onGlobalLayout width="
  + tvTest.getWidth() + " height="
  + tvTest.getHeight());
   }
 });
  }

第四种方式:

private void getSize3() {
    tvTest.post(new Runnable() {

      @Override
      public void run() {
 System.out.println("postDelayed width=" + tvTest.getWidth()
     + " height=" + tvTest.getHeight());
      }
    });

  }

以上就是Android获取View宽高的4种方式,希望对大家的学习有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/163638.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号