How to Vibrate while typing but not when pressing the backspace key
-
21-12-2019 - |
Question
I have the following code:
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
data = (ArrayList<SetRows>)results.values;
EditText etS = (EditText) ((Activity)context).findViewById(R.id.etSearch);
if (data.isEmpty()) {
etS.setTextColor(Color.parseColor("#FFCC0000"));
Vibrator vb = (Vibrator) ((Activity)context).getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 100 milliseconds
vb.vibrate(100);
}
if (!data.isEmpty()) {
etS.setTextColor(Color.parseColor("#FF27497B"));
}
notifyDataSetChanged();
clear();
for(int i = 0, l = data.size(); i < l; i++)
add(data.get(i));
notifyDataSetInvalidated();
}
It vibrates every time I enter a character which doesn't match anything in the ListView
and it's working fine. The issue is, it also vibrates when I press the backspace/delete key. Which is not the intention.
How do I allow the vibrate while entering the wrong letter, but not when pressing backspace/del key. I tried the onTextChanged
but that wasn't working.
Solution
I'd keep the length of entered text. When pressing backspace/delete, you're basically erasing last character (the length is decreasing), so compare the new length with an old one. Pseudocode:
if newLength > oldLength then vibrate
else don't vibrate
If newLength is shorter, it means you have pressed backspace/delete key and deleted a character, so don't vibrate. You can do it in onTextChanged, or where ever makes sense to you.