如下监听键盘状态变化的代码摘自React native的键盘状态监听代码,
这个方法会影响部分性能,正常情况下可以忽略。
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewTreeObserver;
/**
* Keyboard status monitor.
*
* usage:
*
* View view;//View must be had added to the View Tree
*
*
* view.getViewTreeObserver().addOnGlobalLayoutListener(new KeyboardListener(view){
*
* @Override
* public void keyboardStatusChanged(boolean keyboardDidShow, @Nullable KeyboardInfo params){
* if(keyboardDidShow){
* //showing or height changed
* }else{
* //hidden
* }
* }
*
* });
*/
public abstract class KeyboardListener implements ViewTreeObserver.OnGlobalLayoutListener {
private int mKeyboardHeight = 0;
private final Rect mVisibleViewArea = new Rect();
private View view;
private DisplayMetrics mDisplayMetrics;
public KeyboardListener(View view) {
if (view == null) {
throw new NullPointerException("view is null");
}
mDisplayMetrics = view.getContext().getResources().getDisplayMetrics();
this.view = view;
}
@Override
public void onGlobalLayout() {
View rootView = view.getRootView();
if (rootView == null) {
return;
}
rootView.getWindowVisibleDisplayFrame(mVisibleViewArea);
final int heightDiff =
mDisplayMetrics.heightPixels - mVisibleViewArea.bottom;
if (mKeyboardHeight != heightDiff && heightDiff > 0) {
// keyboard is now showing, or the keyboard height has changed
mKeyboardHeight = heightDiff;
KeyboardInfo keyboardInfo = new KeyboardInfo();
keyboardInfo.screenX = mVisibleViewArea.left;
keyboardInfo.screenY = mVisibleViewArea.bottom;
keyboardInfo.width = mVisibleViewArea.width();
keyboardInfo.height = mKeyboardHeight;
sendEvent(true, keyboardInfo);
} else if (mKeyboardHeight != 0 && heightDiff == 0) {
// keyboard is now hidden
mKeyboardHeight = heightDiff;
sendEvent(false, null);
}
}
private void sendEvent(boolean keyboardDidShow, @Nullable KeyboardInfo keyboardInfo) {
keyboardStatusChanged(keyboardDidShow, keyboardInfo);
}
public abstract void keyboardStatusChanged(boolean keyboardDidShow, @Nullable KeyboardInfo params);
public static class KeyboardInfo {
/**
* screen x pixle
*/
public double screenY;
public double screenX;
public double width;
public double height;
}
}
本文介绍了如何在Android中监听键盘的打开和关闭状态,提供了React Native的键盘监听代码示例,并提到了这种方法可能对应用性能产生的影响。
1150

被折叠的 条评论
为什么被折叠?



