After trying all solutions here and on other questions related, Here's the method that works for me:
editText.postDelayed(Runnable { showKeyboard(activity, editText)} , 50)
fun showKeyboard(activity: Activity, editText: EditText) {
val inputMethodManager = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
editText.requestFocus()
inputMethodManager.showSoftInput(this, 0)
}
The fun fact is when you call it without postDeleayed it won't work, even if you just delay it for 1 millisecond it still won't work :D
You can also use it as an extension like this:
fun EditText.showKeyboard(activity: Activity) {
val inputMethodManager = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
requestFocus()
inputMethodManager.showSoftInput(this, 0)
}
if you don't like to pass activity as a parameter, you use this extension function as @Rafols suggests:
fun View.getActivity(): AppCompatActivity? {
var context = this.context
while (context is ContextWrapper) {
if (context is AppCompatActivity) {
return context
}
context = context.baseContext
}
return null
}
then your method will look like this:
fun EditText.showKeyboard() {
val inputMethodManager = getActivity()!!.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
requestFocus()
inputMethodManager.showSoftInput(this, 0)
}
also if you have a text already in your EditText, its better set selection at the end of your existing text:
fun EditText.showKeyboard() {
val inputMethodManager = getActivity()!!.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
requestFocus()
inputMethodManager.showSoftInput(this, 0)
setSelection(length())
}
and if you want to start it when fragment starts:
override fun onResume() {
super.onResume()
editText.postDelayed(Runnable { editText.showKeyboard()} , 50)
}