键盘布局自动上移
发表于|更新于
|阅读量:
接到产品同学的需求,当用户点击控件时,自动调整布局使其上移,避免被软键盘遮挡. 按如下方法实现了:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| final View rootView = findViewById(android.R.id.content); rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { private int mPreviousKeyboardHeight = -1; @Override public void onGlobalLayout() { Rect r = new Rect(); rootView.getWindowVisibleDisplayFrame(r); int screenHeight = rootView.getRootView().getHeight(); int keypadHeight = screenHeight - r.bottom; if (keypadHeight != mPreviousKeyboardHeight) { FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) rootView.getLayoutParams(); if (keypadHeight > screenHeight * 0.15) { params.bottomMargin = keypadHeight; } else { params.bottomMargin = 0; } rootView.setLayoutParams(params); mPreviousKeyboardHeight = keypadHeight; } } });
|