How to listen to EditText?

I have one EditText. I wamt tp do something when the user presses a key Enterwhen changing EditText. How can i do this?

The easiest way:

final EditText edittext = (EditText) findViewById(R.id.edittext);
edittext.setOnKeyListener(new OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        // If the event is a key-down event on the "enter" button
        if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
            (keyCode == KeyEvent.KEYCODE_ENTER)) {
          // Perform action on key press
          Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
          return true;
        }
        return false;
    }
});
+5
source share
5 answers

sample code for text observer

your_edittext.addTextChangedListener(new InputValidator());

    private class InputValidator implements TextWatcher {

        public void afterTextChanged(Editable s) {

        }    
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {                

        }    
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {

        }    
    }    
}
+5
source

First create OnEditorActionListener(for example, as a private instance variable):

private TextView.OnEditorActionListener mEnterListener =
    new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN) { 
                /* If the action is a key-up event on the return key, do something */
            }
        return true;
    });

Then set the listener (i.e. in your method onCreate):

EditText mEditText = (EditText) findViewById(...);
mEditText.setOnEditorActionListener(mEnterListener);
+4
source

:

 your_edittext.addTextChangedListener(new TextWatcher() {

       @Override
       public void afterTextChanged(Editable s) {}

       @Override    
       public void beforeTextChanged(CharSequence s, int start,
         int count, int after) {
       }

       @Override    
       public void onTextChanged(CharSequence s, int start,
         int before, int count) {

       }
      });
+1

TextWatcher. , TextWatcher Android textwatcher API.

0
your_edittext.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //do something
    }

});
-2

All Articles