Search code examples
androidkotlinkeyboardclickfocus

programically click EditText


I would like to programmatically click an editText once a button has been pressed. When a radio button "pitot_area" is selected, I want the editText associated with this selection to be programmatically clicked, so the user has one less "click" on the screen and it happens automatically.

So far I have tried

performClick()
callOnClick()
requestFocus()

the area i would like this code to be within is below:

root.pitot_area.setOnClickListener {
setAreaLabels(root)         
evNodeItem.kvParams = false
evNodeItem.PitotRectArea = false
evNodeItem.PitotRoundArea = false
evNodeItem.areaParams = true

root.area_edit_text.requestFocus()
            

another method I have tried is

root.area_edit_text.setFocusableInTouchMode(true);
                root.area_edit_text.setFocusable(true);
                root.area_edit_text.requestFocus();

for the above lines of code, I have in the .xml file for the editText

android:focusable="false"
android:focusedByDefault="false"

An error does not show and the code builds, it seems this code is not read in kotlin? Does anyone have any ideas on how to do this? Thanks!

edit ive looked at-> Focus Edit Text Programmatically (Kotlin) question sugggested below and was unable to implement it for my code.


Solution

  • To set direct focus to the EditText you have to open keyboard after setting focus to the EditText.

    write this lines into your button click:

    For Activity:

    button.setOnClickListener {
        
        editText.isFocusableInTouchMode = true
        editText.requestFocus()
            
        val inputMethodManager: InputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.toggleSoftInputFromWindow(llMainView.applicationWindowToken, InputMethodManager.SHOW_FORCED, 0)
            
    }
    

    For Fragment:

      button.setOnClickListener {
            
       editText.isFocusableInTouchMode = true
       editText.requestFocus()
    
       val inputMethodManager: InputMethodManager = activity!!.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as InputMethodManager
       inputMethodManager.toggleSoftInputFromWindow(llMainView.applicationWindowToken, InputMethodManager.SHOW_FORCED, 0)
    }