Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focus Edit Text Programmatically (Kotlin)

I have a createEditText function that creates an EditText and adds it to the view. My issue is that once it is added to the view, the user has to tap the EditText in order for the keyboard to be called and editing to work. What I am trying to do is to have it so that once the EditText is created, the user is automatically taken to the edit mode.

In IOS programming, there is a function called becomeFirstResponder() which achieves this. What would the android equivalent be?

Things I have tried:

myEditText.requestFocus()
myEditText.isActivated
myEditText.isFocused
myEditText.isSelected
myEditText.isEnabled
like image 618
marco Avatar asked Jul 05 '26 02:07

marco


2 Answers

Unfortunately it is not enough to call only EditText#requestFocus. In addition to this you also have to call the InputMethodManager#showSoftInput. Following utility method should work:

fun openSoftKeyboard(context: Context, view: View) {
    view.requestFocus()
    // open the soft keyboard
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
like image 132
reVerse Avatar answered Jul 06 '26 17:07

reVerse


This is just an idea (a bit pseudo-code just to clarify things):

myEditText.requestFocus()
(activity or dialog).window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)

You must take care of not showing the soft keyboard if there is a hardware keyboard connected

like image 42
Raymond Arteaga Avatar answered Jul 06 '26 17:07

Raymond Arteaga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!