Search code examples
androidlayoutsizedimension

Fragments - onGlobalLayout() called twice


public class QuadPadFragment extends Fragment {

 int w = 0; int h = 0;

 public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {

    final View view = inflater.inflate(R.layout.quadpadlayout, container, false);

    container.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {  

            h = container.getMeasuredHeight();
            w = container.getMeasuredWidth();
            Log.w("QuadPad Fragment:------", "window width: " + w + "   window height: " + h );

            view.setLayoutParams(new LayoutParams(1, 1));
        }
    });

    return view;
    }
}

I have above class written, everything works fine, but what is puzzling me is why is onGlobalLayout called twice? Im getting this output from Log:

W/QuadPad Fragment:------(27180): window width: 1080   window height: 1
W/QuadPad Fragment:------(27180): window width: 1080   window height: 1

Solution

  • I think it's because you have setLayoutParams. That will call globalLayout again. You have to unregister the listener so it doens't get called twice. The above code will remove the listener.

                @Override
                public void onGlobalLayout() {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        container.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    } else {
                        container.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    }
                    h = container.getMeasuredHeight();
                    w = container.getMeasuredWidth();
                    Log.w("QuadPad Fragment:------", "window width: " + w + "   window height: " + h );
    
                    view.setLayoutParams(new LayoutParams(1, 1));
                }