您的位置:首页 > 移动开发 > Android开发

Android 真正能监听输入法的显示和隐藏

2017-07-03 14:36 736 查看
最近有个需求,就是能监听到输入的弹出与隐藏,并对相应的情况作出,一些界面的变化。

1、监听方法

1、网上虽然有人提供了一些方法,但是对于我不能用,然后自己 google 到一个可行的方法。亲测可行,不过注意,这个方法需要设置 Activity 的输入法模式为 adjustResize , 因为这个模式,才能引起界面的变化。您可以将这段代码 copy 到你的 activity 里面去。注册监听,然后使用。

public interface OnKeyboardVisibilityListener {

void onVisibilityChanged(boolean visible);
}

public final void setKeyboardListener(final OnKeyboardVisibilityListener listener) {
final View activityRootView = ((ViewGroup) mActivity.findViewById(android.R.id.content)).getChildAt(0);

activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

private boolean wasOpened;

private final int DefaultKeyboardDP = 100;

// From @nathanielwolf answer...  Lollipop includes button bar in the root. Add height of button bar (48dp) to maxDiff
private final int EstimatedKeyboardDP = DefaultKeyboardDP + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? 48 : 0);

private final Rect r = new Rect();

@Override
public void onGlobalLayout() {
// Convert the dp to pixels.
int estimatedKeyboardHeight = (int) TypedValue
.applyDimension(TypedValue.COMPLEX_UNIT_DIP, EstimatedKeyboardDP, activityRootView.getResources().getDisplayMetrics());

// Conclude whether the keyboard is shown or not.
activityRootView.getWindowVisibleDisplayFrame(r);
int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
boolean isShown = heightDiff >= estimatedKeyboardHeight;

if (isShown == wasOpened) {
Log.d("Keyboard state", "Ignoring global layout change...");
return;
}

wasOpened = isShown;
listener.onVisibilityChanged(isShown);
}
});
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息