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?
Handle single key events To handle an individual key press, implement onKeyDown() or onKeyUp() as appropriate. Usually, you should use onKeyUp() if you want to be sure that you receive only one event. If the user presses and holds the button, then onKeyDown() is called multiple times.
onKeyDown(int keyCode, KeyEvent event) Called when a key down event has occurred. abstract boolean. onKeyLongPress(int keyCode, KeyEvent event)
The onkeyup attribute fires when the user releases a key (on the keyboard).
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);
CORRECTION:
For a while, I used a generic onKeyListener. I soon found that my code was being called twice. Once with the key down and once with key up. I now use the following listener and only call the code once.
"if (event.getAction() == KeyEvent.ACTION_UP)"
is the key.
OnKeyListener keyListener = new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP) {
//do something here
}
return false;
}
};
I found that onKeyUp()
is called automatically for every control in the Activity. If this is what you want, add it to the Activity just like you add the onCreate()
Example:
public boolean onKeyUp(int keyCode, KeyEvent event) {
//do something here
return false;
};
I know this is a old question, but maybe this will help others with the same issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With