There are 2 ways that Android EditText intercepts and listens for input events:
1. The first method: Use Setonkeylistener (), but this way you can only listen to hard keyboard events.
- EditText. Setonkeylistener(new View). Onkeylistener() {
- @Override
- Public Boolean onKey(View v, int keycode, keyevent Event) {
- TextView. SetText(edittext. GetText());
- Return false;
- }
- });
2. The second method: using the Textwatcher class, this way is able to listen to the soft keyboard and the hard keyboard, we only need to implement the OnTextChanged method, in addition The Textwatcher also provides beforetextchanged and Aftertextchanged methods for more detailed input listening processing.
- EditText. Addtextchangedlistener(new textwatcher() {
- @Override
- Public void ontextchanged(charsequence s, int start, int before, int count) {
- TextView. SetText(edittext. GetText());
- }
- @Override
- Public void beforetextchanged(charsequence s, int start, int count, int after) {
- }
- @Override
- Public void aftertextchanged(Editable s) {
- }
- });
Code snippet: The implementation is not allowed to enter when input to the maximum value, in addition, because EditText does not provide us with EditText's forbidden input function, the following method also implements this function.
- Private void seteditable(EditText medit, int maxLength, Boolean value) {
- If (value) {
- Medit. SetFilters(new inputfilter[] { new myeditfilter( MaxLength) });
- Medit. Setcursorvisible(true);
- Medit. Setfocusableintouchmode(true);
- Medit. Requestfocus();
- }
- else {
- Medit. SetFilters(new inputfilter[] { new inputfilter() {
- @Override
- public charsequence (charsequence Source int Start,int end, spanned Dest, int Dstart, int DEnd { /span>
- return source. Length() < 1 dest. Subsequence(dstart, dend) : " ";
- }
- } });
- Medit. Setcursorvisible(false);
- Medit. Setfocusableintouchmode(false);
- Medit. Clearfocus();
- }
- }
Android EditText intercept and listen for input events