Caroline
Caroline

Reputation: 3913

EditText + Button onClick when the user press enter

I have the following structure in my main layout:

 LinearLayout
      EditText
      EditText
      Checkbox
      Button

I'd like that "enter" key at the second EditText to cast a onClick event at the button. How can I do it? Is possible to do it with only changing the xml?

Thanks in advance

Upvotes: 0

Views: 1659

Answers (2)

Ron
Ron

Reputation: 24235

You can use this

((EditText)findViewById(R.id.edittext)).setOnEditorActionListener(
    new EditText.OnEditorActionListener() {
  @Override
  public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
      if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
          mButton.performClick(); 
          return true;
      }
      return false;
   }
});

Upvotes: 2

Alex Florescu
Alex Florescu

Reputation: 5151

You can set the behavior for clicking the button in XML. Make a method with the behavior you want to have happen when the button is clicked. Then, call it for the button by using android:onClick

For the EditText, I believe you can't do it in XML and have to do it as in the answer from user7777777777.

Upvotes: 1

Related Questions