欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

4種Android獲取View寬高的方式

 更新時(shí)間:2016年01月07日 10:58:09   投稿:lijiao  
這篇文章主要介紹了4種Android獲取View寬高的方式

有時(shí)我們會(huì)有基于這樣的需求,當(dāng)Activity創(chuàng)建時(shí),需要獲取某個(gè)View的寬高,然后進(jìn)行相應(yīng)的操作,但是我們?cè)趏nCreate,onStart中獲取View的大小,獲取到的值都是0,只是由于View的繪制工程還未完成,和在onCreate中彈出Dialog或者PopupWindow會(huì)報(bào)一個(gè)Activity not running原理類似。

接下來就為大家介紹幾種獲取View寬高的方法:
第一種方式:重寫Activity中的onWindowFocusChanged,當(dāng)Activity獲取到焦點(diǎn)的時(shí)候View已經(jīng)繪制完成,也能獲取到View的準(zhǔn)確寬高了。同樣的Dialog和PopupWindow也可以在這里彈出,需要注意的是這個(gè)方法會(huì)調(diào)用多次,當(dāng)hasFocus為true時(shí),才可進(jìn)行相應(yīng)的操作

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

第二種方式:

/**
   * 會(huì)執(zhí)行多次
   */
  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種方式,希望對(duì)大家的學(xué)習(xí)有所幫助。

相關(guān)文章

最新評(píng)論