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

前端 未结 10 590
无人及你
无人及你 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条回答
  • 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() })
    
    0 讨论(0)
  • 2020-11-29 18:36

    add the following line in edittext

    android:imeOptions="actionDone"
    

    Happy coding

    0 讨论(0)
  • 2020-11-29 18:37

    This is how it is done

    editText.setOnEditorActionListener(new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if(actionId == EditorInfo.IME_ACTION_DONE){
                //do something
            }
            return false;
       }
    });
    

    Don't forget to add following

    <EditText android:layout_height="wrap_content"
    
        android:layout_width="wrap_content"
    
        android:imeOptions="actionDone"/>
    

    actionDone in your EditText.

    0 讨论(0)
  • 2020-11-29 18:39

    In your XML file inside your edittext tag add below snippet

    android:imeOptions="actionDone"
    

    Then inside your Java class, write the below code

    editText.setOnEditorActionListener(new EditText.OnEditorActionListener() { 
        @Override 
        public boolean onEditorAction(TextView v, int id, KeyEvent event) { 
            if (id == EditorInfo.IME_ACTION_DONE) { 
                //do something here 
                return true;
            }
            return false; 
        } 
    });
    
    0 讨论(0)
提交回复
热议问题