I followed this example (https://medium.com/@ali.muzaffar/building-a-pinentryedittext-in-android-5f2eddcae5d3) to create a PinEntryEditText in my app. What I want, is to display the keyboard every single time I open the activity containing the PinEntryEditText. I'm doing this by requesting focus in the onResume
method.
The problem is that the keyboard doesn't appear when opening a new activity and returning back to the activity containing the PinEntryEditText.
What could be the issue here?
override fun onResume() {
super.onResume()
pinEntry_editText.post { pinEntry_editText.requestFocus() }
}
This is what I've tried:
setting focusable/focusableInTouchMode in XML
setting focusable/focusableInTouchMode in the onResume
method
created a function inside the PinEntryEditText
containing requestFocus
/focusable
/focusableInTouchMode
and called it in the onResume
method
calling this function in the onResume
method:
fun AppCompatEditText.requestKeyboardFocus() {
val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
In AndroidManifest
I added this line to my activity:
android:windowSoftInputMode="adjustResize" />
I will suggest listening for current focus changes and force show the keyboard. first add a showSoftKeyboard fun:
private fun showSoftKeyboard(view: View) {
if (view.requestFocus()) {
val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
// here is one more tricky issue
// imm.showSoftInputMethod doesn't work well
// and imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0) doesn't work well for all cases too
imm?.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
}
}
Update your onResume fun:
override fun onResume() {
super.onResume()
currentFocus?.let {
showSoftKeyboard(it)
}
pinEntry_editText.requestFocus()
}
**
pinEntry_editText.post { // Do work on UI Thread }
This is useful when we are not on UI thread and we want to switch back to make some UI change, so there is no need for that in this case since onResume will be called on the UI thread.