I'm working on an Android application and have a view with 3 EditTexts. What I'm trying to achieve is that on a numeric key being pressed in the last one should call the okKey event for that activity. The problem is that for the EditText on which I set the onKeyListener, neither getText nor setText methods work. Allow me to explain:
Suppose I initialize an empty string
String string1 = "";
In my onCreate method, I set the onKeyListener on one of the EditTexts
@Override
public void onCreate(Bundle savedInstanceState) {
...
findViewById(R.id.EditText3).setOnKeyListener(this);
...
}
Now, if I write the following code in the overriding okKey method
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode >= KeyEvent.KEYCODE_0 && keyCode <= KeyEvent.KEYCODE_9) {
string1 += ((EditText) findViewById(R.id.EditText1)).getText();
string1 += ((EditText) findViewById(R.id.EditText2)).getText();
string1 += ((EditText) findViewById(R.id.EditText3)).getText();
((EditText) findViewById(R.id.EditText1)).setText("");
((EditText) findViewById(R.id.EditText2)).setText("");
((EditText) findViewById(R.id.EditText3)).setText("");
}
return false;
}
Only EditText1 and EditText2 get cleared and the text in EditText3 does not get concatenated to string1. If I replace the condition of the If statement with
if (keyCode == KeyEvent.KEYCODE_ENTER)
then on pressing Enter key (set as Next), it works as expected. I tried to add the setText("") in the onResume method of the activity too but with no difference in the result. I appreciate the time you took to read my question!
Edited: Added the "return false;" at the end of onKey method, I had it in my work but missed putting it in this question, was reminded by Chris's answer.
In addition to Chris' answer, a check should be added to insure that event.getAction() is equal to KeyEvent.ACTION_UP; onKey gets called twice, and if getAction() is ACTION_DOWN (first time the method is called), the character won't yet have been added to the CharSequence returned by getText().