Determining the size of an Android view at runtime

前端 未结 12 2032
陌清茗
陌清茗 2020-11-22 09:59

I am trying to apply an animation to a view in my Android app after my activity is created. To do this, I need to determine the current size of the view, and then set up an

12条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 10:22

    Use the ViewTreeObserver on the View to wait for the first layout. Only after the first layout will getWidth()/getHeight()/getMeasuredWidth()/getMeasuredHeight() work.

    ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
    if (viewTreeObserver.isAlive()) {
      viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
          view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
          viewWidth = view.getWidth();
          viewHeight = view.getHeight();
        }
      });
    }
    

提交回复
热议问题