Search code examples
javaandroidonkeyup

Android Development: How To Use onKeyUp?


I'm new to Android development and I can't seem to find a good guide on how to use an onKeyUp listener.

In my app, I have a big EditText, when someone presses and releases a key in that EditText I want to call a function that will perform regular expressions in that EditText.

I don't know how I'd use the onKeyUp. Could someone please show me how?


Solution

  • The very right way is to use TextWatcher class.

    EditText tv_filter = (EditText) findViewById(R.id.filter);
    
    TextWatcher fieldValidatorTextWatcher = 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) {
                if (filterLongEnough()) {
                    populateList();
                }
            }
    
            private boolean filterLongEnough() {
                return tv_filter.getText().toString().trim().length() > 2;
            }
        };
        tv_filter.addTextChangedListener(fieldValidatorTextWatcher);