4種Android擷取View寬高的方式_Android

來源:互聯網
上載者:User

有時我們會有基於這樣的需求,當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種方式,希望對大家的學習有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.