android - 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)
}
解决方案
尝试这个 :
focusedView.requestFocus();
focusedView.postDelayed(new Runnable() {
@Override
public void run() {
InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.showSoftInput(focusedView, 0);
}
}, 100);
推荐阅读
- javascript - 如何在数据表中添加行?
- jquery - 根据一个 json 结果生成单独的 html
- regex - apache 2.4 LocationMatch 没有捕捉到
- android - onMessageReceived 未在 Android 上调用
- java - android会为了释放内存而杀死单例吗?
- c# - 如何更新表单字段
- scala - 在Scala中使用Ordered[String]对字符串进行排序?
- javascript - react-bootstrap-table - 具有自己数据的列(不是来自数据集)
- c++ - 向量的高效移动
- ios - 带有动态高度单元格和动态内容swift 4的tableview单元格内的Collectionview