首页 > 解决方案 > Restore focus to input after configuration change

问题描述

I am trying to implement logic that restores focus to input after configuration has changed. I couldn't find any official documentation of how to do this, I am trying to do it myself like this:

My focusable views have unique tags e.g. android:tag="note_input"

And then I have this view of code, which almost works, input is in fact focused, but the software keyboard is not being displayed.

// 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)
}

标签: android

解决方案


尝试这个 :

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

推荐阅读