3
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
Marcel50506
  • 1,280
  • 1
  • 14
  • 32
Axel Stone
  • 1,521
  • 4
  • 23
  • 43

1 Answers1

11

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));
            }
Pedro Oliveira
  • 20,442
  • 8
  • 55
  • 82