Activate button event when giving enter in an edit

1

I created a "register" screen where the user informs the name / surname and where there is a Continue button that goes to another screen. I would like this new screen to open when the user hit Enter, but I do not know how to make the Enter key have this function.

Below the home screen code

public class CadastroActivity extends AppCompatActivity {

EditText edtNome;

Button btnContinuar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cadastro);

    edtNome = (EditText) findViewById(R.id.edtNome);

    btnContinuar = (Button) findViewById(R.id.btnContinuar);

    btnContinuar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent EnviarDados = new Intent(CadastroActivity.this, ResultadoActivity.class);

            String txtNome = edtNome.getText().toString();

            Bundle bundle = new Bundle();

            bundle.putString("nome", txtNome);

            EnviarDados.putExtras(bundle);

            startActivity(EnviarDados);

        }
    });
}

}

    
asked by anonymous 26.10.2017 / 04:48

1 answer

2

The best practice to achieve this is to use the setOnEditorActionListener of EditText event as shown this answer or from here .

You will need to configure EditText in XML (if you have not done so) with the imeOptions corresponding to "next field".

<EditText
    android:id="@+id/editText2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:maxLines="1"
    android:imeOptions="actionNext" />

Note that here we set the maxLines="1" property, which will cause Android to know that pressing the Enter should advance the field. The android:imeOptions="actionNext" changes the drawing of the "Enter" button with an arrow, indicating to the user that clicking on it will be taken to the next field / screen / etc. Setting this property in XML also sets the Edit event ID so you can perform the action you want.

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_NEXT) {
            callAnotherActivity();
            return true;
        }
        return false;
    }
});
    
26.10.2017 / 05:53