更改配置后将焦点恢复为输入

时间:2018-07-16 13:19:44

标签: android

我正在尝试实现在配置更改后将焦点恢复到输入的逻辑。我找不到有关如何执行此操作的任何官方文档,我正在尝试自己这样做:

我的焦点视图具有唯一的标签,例如android:tag =“ note_input”

然后我有这种代码视图,几乎可以正常工作,实际上输入是针对输入的,但未显示软件键盘。

// fetch InputMethodManager in onCreate method
imm = activity!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager


override fun onSaveInstanceState(outState: Bundle) {
    val focusedViewTag: String? = activity!!.currentFocus.tag?.toString()
    if (focusedViewTag != null) {
        outState.putString(ARG_FOCUSED_VIEW, focusedViewTag)
    }

    super.onSaveInstanceState(outState)
}


override fun onViewStateRestored(savedInstanceState: Bundle?) {
    val focusedViewTag = savedInstanceState?.getString(ARG_FOCUSED_VIEW)
    val focusedView = binding.root.findViewWithTag<View?>(focusedViewTag)
    if (focusedView != null) {
        focusedView.requestFocus()        // this part works
        imm.showSoftInput(focusedView, 0) // this doesn't work
    }

    super.onViewStateRestored(savedInstanceState)
}

1 个答案:

答案 0 :(得分:0)

尝试:

                focusedView.requestFocus();
            focusedView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(focusedView, 0);
                }
            }, 100);