Android--监听软键盘弹出隐藏事件
网上大多是通过使用ViewTreeObserver.OnGlobalLayoutListener监听全局布局变化,实现了键盘弹出时获取其高度来判断,但是在部分机型不准确,而且也影响性能;
private final ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener =new ViewTreeObserver.OnGlobalLayoutListener() {@Overridepublic void onGlobalLayout() {if (!isActivityValid() || onKeyBoardChangeListener == null) {return;}try {Rect rect = new Rect();weakActivity.get().getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);int screenHeight = weakActivity.get().getWindow().getDecorView().getHeight();int keyBoardHeight = screenHeight - rect.bottom;onKeyBoardChangeListener.OnKeyBoardChange(keyBoardHeight > 0, keyBoardHeight);} catch (Exception e) {Log.e(TAG, "onGlobalLayout error:" + e.getMessage());}}};
实现一:
通过重写WindowInsetsAnimation.Callback获取实时输入法高度处理
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {View rootView = getWindow().getDecorView().getRootView();rootView.setWindowInsetsAnimationCallback(new WindowInsetsAnimation.Callback() {@NonNull@Overridepublic WindowInsets onProgress(@NonNull WindowInsets windowInsets, @NonNull List<WindowInsetsAnimation> list) {Insets insets = windowInsets.getInsets(WindowInsets.Type.ime());int imeHeight = insets.bottom;//imeHeight > 0表示软键盘正在显示;imeHeight == 0表示软键盘隐藏if (imeHeight == 0) {//执行要做的事情}return null;}});}
实现二:
重写setOnApplyWindowInsetsListener
getWindow().getDecorView().setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {@NonNull@Overridepublic WindowInsets onApplyWindowInsets(@NonNull View view, @NonNull WindowInsets windowInsets) {Insets insets = windowInsets.getInsets(WindowInsets.Type.ime());int imeHeight = insets.bottom;return null;}});