4 ways for Android to obtain View width and height

  • 2020-12-16 06:06:50
  • OfStack

Sometimes we will be based on the demand, when Activity created, need to get some View width is high, and then to carry on the corresponding operation, but we in onCreate onStart derive View size, access to the value is 0, only because View mapping project has yet to be completed, and in the onCreate pop-up Dialog or PopupWindow will quote a Activity not running similar principle.

Here are some methods to obtain the width and height of View:
The first way: rewrite onWindowFocusChanged in Activity so that when Activity gets the focus, View has been drawn and the exact width and height of View can be obtained. The same Dialog and PopupWindow can pop up here, but note that this method is called multiple times and only works when hasFocus is true


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

The second way:


/**
   *  It will be executed multiple times 
   */
  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;
      }

    });
  }

The third way:


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

The fourth way:


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

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

  }

Above is Android to obtain View width and height in 4 ways, hope to be helpful to your study.


Related articles: