片段 - onGlobalLayout()调用两次

时间:2014-10-08 15:31:59

标签: android layout size dimension

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;
    }
}

我上面写的课程,一切正常,但令我困惑的是为什么onGlobalLayout被调用两次?我从Log得到了这个输出:

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

1 个答案:

答案 0 :(得分:6)

我认为这是因为你有setLayoutParams。这将再次调用globalLayout。您必须取消注册侦听器,以便不会被调用两次。上面的代码将删除监听器。

            @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));
            }