view--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());
      }
    });

  }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM