10

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 this problem,

getWidth work only onWindowFocusChanged.

 public void onWindowFocusChanged(boolean hasFocus) { }

but Fragment do not have this method.

How to get View width in Fragment?

dmnlk
  • 2,995
  • 2
  • 25
  • 30

2 Answers2

10

I'd had a similar problem and solved it in the Fragment callback onViewCreated() like this:

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    view.post(new Runnable() {
        @Override
        public void run() {
            // do operations or methods involved
            // View.getWidth(); or View.getHeight();
            // here
        }
    });
}

run() runs after all views were rendered...

Andrew
  • 36,676
  • 11
  • 141
  • 113
8

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);
    }
  });
Community
  • 1
  • 1
GrIsHu
  • 29,068
  • 10
  • 64
  • 102
  • This works but I really hate this approach, makes for bloated code. Just wish there was an en event for when everything is finished layout for a fragment. – Placeable Apr 30 '18 at 09:59