Google Pixel设备Android 13后软键盘隐藏按钮与返回键行为差异
Android 13(Pixel设备)软键盘隐藏按钮与
onKeyPreIme的问题解决 一、这是Android 13的系统改动吗?
是的,这属于Android 13的系统行为变更。在Android 13及后续版本中,点击软键盘右下角的隐藏按钮(向下箭头图标)不再触发onKeyPreIme方法——系统将这个操作归类为输入法内部的状态变更,而非传统按键事件,因此不再走之前的按键事件分发逻辑。
二、如何在点击软键盘隐藏按钮时注入自定义代码?
推荐以下几种可行方案:
方案1:使用WindowInsets监听软键盘状态(推荐,现代API)
利用Android官方提供的WindowInsets API直接监听软键盘显示/隐藏状态,是最可靠的实现方式:
// 在Activity的onCreate方法中添加监听 getWindow().getDecorView().setOnApplyWindowInsetsListener((view, insets) -> { // 判断软键盘是否可见 boolean isImeVisible = insets.isVisible(WindowInsets.Type.ime()); if (!isImeVisible) { // 软键盘隐藏时执行你的自定义逻辑 yourCustomMethod(); } return insets; });
方案2:监听布局变化判断软键盘状态
通过监听根布局的尺寸变化,间接判断软键盘是否隐藏:
View rootView = getWindow().getDecorView().getRootView(); rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Rect visibleFrame = new Rect(); rootView.getWindowVisibleDisplayFrame(visibleFrame); int screenHeight = rootView.getHeight(); // 计算软键盘高度,阈值设为屏幕高度的15%,可根据需求调整 int imeHeight = screenHeight - visibleFrame.bottom; if (imeHeight < screenHeight * 0.15) { // 软键盘已隐藏,执行自定义代码 yourCustomMethod(); // 可选:如果只需要监听一次,可移除监听避免重复触发 rootView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } } });
方案3:自定义EditText监听焦点变化(补充方案)
通过重写EditText的焦点变化方法,结合输入法状态判断,适合EditText相关场景:
public class CustomEditText extends EditText { public CustomEditText(Context context) { super(context); } public CustomEditText(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { super.onFocusChanged(focused, direction, previouslyFocusedRect); if (!focused) { InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null && !imm.isActive(this)) { // 软键盘已隐藏,执行自定义逻辑 yourCustomMethod(); } } } }
内容的提问来源于stack exchange,提问作者Aman Singh
相关产品推荐
相关产品推荐

