How do listen EditText?

前端 未结 5 1699
小蘑菇
小蘑菇 2020-12-19 10:27

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

相关标签:
5条回答
  • 2020-12-19 10:46

    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) {
    
            }    
        }    
    }
    
    0 讨论(0)
  • 2020-12-19 10:46
    your_edittext.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //do something
        }
    
    });
    
    0 讨论(0)
  • 2020-12-19 10:47

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

    0 讨论(0)
  • 2020-12-19 11:00

    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) {
    
           }
          });
    
    0 讨论(0)
  • 2020-12-19 11:08

    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);
    
    0 讨论(0)
提交回复
热议问题