Implicit “Submit” after hitting Done on the keyboard at the last EditText

前端 未结 10 634
无人及你
无人及你 2020-11-29 17:51

I\'ve used some apps where when I fill my username, then go to my password, if I hit \"Done\" on the keyboard, the login form is automatically submitted, without me having t

10条回答
  •  旧时难觅i
    2020-11-29 18:34

    Simple and effective solution with Kotlin

    Extend EditText:

    fun EditText.onSubmit(func: () -> Unit) {
        setOnEditorActionListener { _, actionId, _ ->
    
           if (actionId == EditorInfo.IME_ACTION_DONE) {
               func()
           }
    
           true
    
        }
    }
    

    Then use the new method like this:

    editText.onSubmit { submit() }
    

    Where submit() is something like this:

    fun submit() {
        // call to api
    }
    

    More generic extension

    fun EditText.on(actionId: Int, func: () -> Unit) {
        setOnEditorActionListener { _, receivedActionId, _ ->
    
           if (actionId == receivedActionId) {
               func()
           }
    
            true
        }
    }
    

    And then you can use it to listen to your event:

    email.on(EditorInfo.IME_ACTION_NEXT, { confirm() })
    

提交回复
热议问题