Collection of 4 Methods for Obtaining Width and Height of Controls in Android

  • 2021-08-17 01:10:54
  • OfStack

Learn from self-development art

1.onWindowFocusChanged

This method is called several times, after View is initialized, and once when the window of Activity gets focus and loses focus (Activity continues and pauses).


@Override
public void onWindowFocusChanged(boolean hasFocus) {
  super.onWindowFocusChanged(hasFocus);
  if (hasFocus) {
    int width = view.getMeasuredWidth();
    int height = view.getMeasuredHeight();
  }
}

2.view.post


@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  ViewGroup root = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.activity_main, null, false);
  setContentView(root);
  final View view = root;
  view.post(new Runnable() {
    @Override
    public void run() {
      int width = view.getMeasuredWidth();
      int height = view.getMeasuredHeight();
      Log.i(TAG, width + " " + height);
    }
  });
}

I don't know the specific principle for the time being, but after the asynchronous callback of view encapsulation is initialized, the mapping of view is mostly completed, which is a synchronous process. That's why you can receive messages.

3.ViewTreeObserver

He has many callbacks. For example, the onGlobalLayout method will be called back when the state of the View tree changes or the View visibility within the View tree changes.


final View view = root;
ViewTreeObserver observer = view.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
  @Override
  public void onGlobalLayout() {
    view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
    int width = view.getMeasuredWidth();
    int height = view.getMeasuredHeight();
    Log.i(TAG, width + " " + height);
  }
});

Obtain the observed message by adding global and removing listener.

4.view.measure

Manual mapping, divided into three situations:

1. match_parent

This situation is not available. Constructing MeasureSpec in this case requires knowing the remaining space of the parent container.

2. Specific values (dp/px)

For example, the width and height are all 100px, which can be done as follows:


View view = root;
int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY);
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY);
view.measure(widthMeasureSpec, heightMeasureSpec);
Log.i(TAG, widthMeasureSpec + " " + heightMeasureSpec);

So far, this method is not recommended, because there are errors found in the measurement.


Related articles: