这是我xml中最顶层的ll
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rootLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/blue_bg"
android:gravity="center_horizontal"
android:orientation="vertical" >
然后我使用这段代码:
private void setKeyboardVisibilityListener()
{
final View root = findViewById(R.id.rootLayout);
root.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// TODO Auto-generated method stub
View continueButton = findViewById(R.id.continueButton);
int heightDiff = root.getRootView().getHeight() - root.getHeight();
if (heightDiff > 100) { // more than 100 pixels is probably a keyboard
// keyboard is shown
mInputBox.setBackgroundResource(R.drawable.input_box_active);
} else {
// keyboard is not shown
mInputBox.setBackgroundResource(R.drawable.input_box_idle);
}
}
});
}
但是当软键盘进入和出现时,我总是得到heightDiff == 50
答案 0 :(得分:0)
我为我的要求制作了这个Singleton帮助程序类,因此您可以根据需要轻松移植它:
public final class SoftInputUtils {
private transient SoftReference<View> mView;
private int mLastHeightDifference = 0;
public void startDetectingSoftInput(final View view) {
if (view.getViewTreeObserver().isAlive()) {
mView = new SoftReference<View>(view);
if (mView.get() != null) {
View v = mView.get();
v.getViewTreeObserver().addOnGlobalLayoutListener(
new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
checkPotentialSoftInputVisibility();
}
});
}
}
}
private void checkPotentialSoftInputVisibility() {
if (mView != null && mView.get() != null) {
View v = mView.get();
Rect r = new Rect();
v.getWindowVisibleDisplayFrame(r);
int screenHeight = v.getRootView().getHeight();
int heightDifference = screenHeight - (r.bottom - r.top);
// Soft input potentially got visible, so we readjust view height
if (heightDifference > screenHeight / 5
&& heightDifference != mLastHeightDifference) {
ViewGroup.LayoutParams lp = (ViewGroup.LayoutParams) v
.getLayoutParams();
lp.height = screenHeight - heightDifference;
v.requestLayout();
mLastHeightDifference = heightDifference;
} else if (heightDifference != mLastHeightDifference) {
// And now most likely not visible so adjust height back
ViewGroup.LayoutParams lp = (ViewGroup.LayoutParams) v
.getLayoutParams();
lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
v.requestLayout();
mLastHeightDifference = heightDifference;
}
}
}
}