android EditText imeOption OnClick

2.5k views Asked by At

With a Button it is simple,

<Button 
    android:blablabla="blabla"
    ...
    android:onClick="doSomething" />

this will preform the doSomething(View) function.

How can we mimic this with an EditText ? I have read about this and i read that most people use an imeOptions (which still seems necessary) and then implement a actionListener on that EditText object.

This is were i'm lost. Is there a way to implement the "Done"-action (or send or...) from our keyboard to a onClick function like we do with a Button, or do we need to explicitly implement the listener ?

Regards !

3

There are 3 answers

1
Alex On

I am assuming what you are wanting to do is run some code when the EditText is clicked?

If so, I have found a solution from another thread on the site:

    EditText myEditText = (EditText) findViewById(R.id.myEditText);
    myEditText.setOnFocusChangeListener(new OnFocusChangeListener() {

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {

    then do this code here

    }
}
});

via: A better way to OnClick for EditText fields?

2
codePG On

The below code will perform some action when you press the Done key in the softkeyboard.

editText.setOnEditorActionListener(new OnEditorActionListener() {        
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if(actionId==EditorInfo.IME_ACTION_DONE){
            //do your actions here that you like to perform when done is pressed
            //Its advised to check for empty edit text and other related 
            //conditions before preforming required actions
        }
    return false;
    }
});

Hope it helps !!

0
Leonardo Sibela On

Kotlin version

editText.setOnEditorActionListener { view, actionId, event -> 
    if(actionId==EditorInfo.IME_ACTION_DONE){
        // do your actions here that you like to perform when done is pressed
        true // return true from your lambda when the action is treated
    }
    false // return false from your lambda when the action is not treated
}

Java version

editText.setOnEditorActionListener(new OnEditorActionListener() {        
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if(actionId==EditorInfo.IME_ACTION_DONE){
            //do your actions here that you like to perform when done is pressed
            return true; // return true when the action is treated
        }
        return false; // return false when the action is not treated
    }
});