Listener for Done button on EditText and clear EditText when user not press Done button?

Viewed 4513

I have an EditText and I want to listen for if the user presses the "done" button on the keypad and I also want to clear EditText when user not presses the "done" button on the softkeypad , how would I do this?

2 Answers

To check user pressed "Done" button of soft keyboard, use the code below:

edittext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
        if(i== EditorInfo.IME_ACTION_DONE){
            Toast.makeText(getApplicationContext(),"Done pressed",Toast.LENGTH_SHORT).show();
        }
        return false;
    }
});

To clear the text of edittext once focus has been changed, use the code below:

edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if(!hasFocus){
            edittext.setText("");
        }
    }
});

In Kotlin like so:

android:imeOptions="actionDone"

edittext.onFocusChangeListener = OnFocusChangeListener { view, hasFocus ->
                if (hasFocus) {
                    //Logic Here
                }
            }
Related