Inc*_*ble 2 size layout android 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;
}
}
Run Code Online (Sandbox Code Playgroud)
我上面写的课,一切正常,但令我困惑的是为什么onGlobalLayout被调用了两次?我得到这个输出Log:
W/QuadPad Fragment:------(27180): window width: 1080 window height: 1
W/QuadPad Fragment:------(27180): window width: 1080 window height: 1
Run Code Online (Sandbox Code Playgroud)
我认为这是因为你有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));
}
Run Code Online (Sandbox Code Playgroud)