I have an edit text which functions as a search box in my application. In Jelly Bean on my Nexus 7 when I type something into the text box which I am listening on and hit enter the KeyEvent = null and ActionId = 0 passed into the onEditorAction() method. Has anyone else encountered this? I'm thinking it might be a bug.
In the second if statement below I get a null pointer because the actionId = 0 and KeyEvent = null;
// Search field logic.
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
Log.d(TAG, "onEditorAction");
if (event != null && event.getAction() != KeyEvent.ACTION_DOWN)
return false;
if (actionId == EditorInfo.IME_ACTION_SEARCH
|| event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
.....Do some stuff();
}
}
Ended up adding in a null check for KeyEvent. Thanks to commonsware for pointing out this happens on 3.0+. Seems more like a workaround then a solution, but it works.
Beside
KeyEvent.ACTION_UP
we also need to captureKeyEvent.ACTION_DOWN
. UnlessKeyEvent.ACTION_UP
will never be passed toEditText
so ouronEditorAction
will not work. Example:You have to replace
EditorInfo.IME_ACTION_DONE
to correct version ofEditorInfo.IME_ACTION_
according toandroid:imeOptions="actionNext"
It might be worth noting, that you can get more than one event for the click on Enter (depending on the android version). One for the KeyDown (KeyEvent.ACTION_DOWN), one for the KeyUp (KeyEvent.ACTION_UP). When I forgot to check that I accidentally started two server calls for the same action.
You dont discover the truth, if you customize return key. You need both set imeActionLabel and imeActionId in your layout. Such as:
In your java code:
It will work fine.
I found that my "bug-like behavior" was due to
imeActionLabel
complicating things. I only used it because it was mentioned in the Text Fields Guide as a way to have a custom return key label. Here are the results of my tests in Lollipop,Case 1: default, return key symbol = closing angle bracket
onEditorAction is called once.
EditorInfo.IME_ACTION_NEXT
Case 2:
imeOptions
, return key symbol = checkmarkonEditorAction is called once.
EditorInfo.IME_ACTION_DONE
Case 3:
imeActionLabel
, return key symbol = "URdone"onEditorAction can be called more than once.
KeyEvent = null, actionId = 0
KeyEvent =
KeyEvent.ACTION_DOWN
, actionId = 0KeyEvent =
KeyEvent.ACTION_UP
, actionId = 0NOTES:
I'm not sure if actionId = 0 is from
EditorInfo.IME_ACTION_UNSPECIFIED
orEditorInfo.IME_NULL
.If the next focusable is non-editable, the return key symbol becomes a left pointing arrow.
You can also use
setOnFocusChangeListener
to overrideonFocusChange
, which will be called according to the above cursor behavior.