When should I get Width View in Fragment

前端 未结 2 1741
一向
一向 2021-02-08 21:36

I adding View (button) programally in Linearlayout.LinearLayout is layouted by XML in Fragment.

I want to get button width, but always return 0.

I googled thi

2条回答
  •  悲&欢浪女
    2021-02-08 21:43

    Check out post GlobalLayoutListener. You can use the listener on your Button in onCreateView() as you have used onWindowFocusChanged. It also is more reliable than onWindowFocusChanged().

    Try out as below:

      final View myView = profileContainer.findViewById(R.id.sub_page_padding);
      ViewTreeObserver vto = profilePadding.getViewTreeObserver();
      vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
          Log.d("TEST", "Height = " + myView.getHeight() + " Width = " + myView.getWidth());
          ViewTreeObserver obs = profilePadding.getViewTreeObserver();
          obs.removeGlobalOnLayoutListener(this);
        }
      });
    

提交回复
热议问题