How do listen EditText?

2019-01-26 14:02发布

问题:

I have a EditText. I wamt tp do something, when the user presses the Enter key while changing EditText. How can I do that?

The most simplest method:

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;
    }
});

回答1:

sample code for text watcher

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) {

        }    
    }    
}


回答2:

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

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 onCreate method):

EditText mEditText = (EditText) findViewById(...);
mEditText.setOnEditorActionListener(mEnterListener);


回答3:

Another alternative is:

 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) {

       }
      });


回答4:

You need to use TextWatcher for this purpose. Here is an example on how to work with TextWatcher and Android textwatcher API.



回答5:

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

});