如何收听 EditText?

2022-01-14 00:00:00 android java android-edittext

我有一个 EditText.当用户在更改 EditText 时按下 Enter 键时,我想做点什么.我怎样才能做到这一点?

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

最简单的方法:

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

推荐答案

文本观察器示例代码

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

        }    
    }    
}

相关文章