在 Fragment 中显示/隐藏软键盘事件

Tom*_*mCB 5 android android-softkeyboard

有很多关于查找显示/隐藏软键盘事件的帖子。我发现自己处于需要根据片段中的软键状态更改图标的情况。

我尝试实现 onMeasure,但无法在片段中覆盖它。是否有一种(相对)无痛的方法可以在我的片段中获得干净的显示/隐藏软键盘事件,或者我应该放弃发货?

Art*_*Art 1

可悲的是,但事实是 - Android 没有本机软件键盘显示事件。

处理键盘隐藏事实的一种方法是检查输入的符号和后退按钮按下(例如 textEdit 甚至会收到后退按钮) - 但这不是足够灵活的解决方案。

另一种可能的解决方案是:覆盖 Activity 中的 onMeasure,然后通知观察者(模式 Observer)——例如片段。Fragment 应该自己订阅和取消订阅 onPause onResume 事件。活动代码类似:

private class DialogActivityLayout extends LinearLayout {

        public DialogActivityLayout(Context context, AttributeSet attributeSet) {
            super(context, attributeSet);
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            inflater.inflate(R.layout.activity_dialog, this);
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            final int proposedHeight = MeasureSpec.getSize(heightMeasureSpec);
            final int actualHeight = getHeight();

            /* Layout loaded */
            if (actualHeight == 0 || proposedHeight == actualHeight) {
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
                return;
            }

            if (proposedHeight > actualHeight) {
                DialogActivity.this.onKeyboardHide();
            } else {
                DialogActivity.this.onKeyboardShow();
            }
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
Run Code Online (Sandbox Code Playgroud)

我不确定,但我记得它仅适用于 LinearLayout,当然活动应该adjustResize设置标志(以编程方式或在清单中)

另一种(我认为更好的方法)是与 globalTree 观察者一样

Android 活动中的 SoftKeyboard 打开和关闭侦听器?