I am developing an Android app. I have written my own code for back key event. For that i am catching events using this method public boolean onKeyDown(int keyCode, KeyEvent event) .....
I also want to use Menu options I have used Inflator for that. But when I click on menu button, that event caught by my onKeyDown method.
I am not expecting that, I expect to execute following methods,
public boolean onCreateOptionsMenu(Me开发者_如何转开发nu menu){ // creating menu using MenuInflator }
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case :
return true;
default:
}
}
How could I use both the things on the same activity?? Any Idea ???
According to the documentation of onKeyDown()
:
it is normal that it receives the 'menu button pressed' event, as any
KeyEvent
but if you return
false
, this event will continue to be propagated and will therefore leadonOptionsItemSelected()
to be called
So you should code your onKeyDown()
in a way that lets the KeyEvent
to propagate if you do not handle it on your own.
In the following example, we have two keys that are interesting to us: one we fully handle on our own, one we just track, and we ignore all the rest:
protected boolean onKeyDown(int keyCode, KeyEvent event) {
boolean handled = false; // By default we let the event propagation turned on
if (keyCode == A_KEY_YOU_WOULD_LIKE_TO_HANDLE_BY_YOURSELF) {
doSomething();
handled = true; // Stops the event propagation
}
else if (keyCode == A_KEY_YOU_WOULD_LIKE_TO_TRACK_WITHOUT_PREVENTING_THE_SYSTEM_FROM_HANDLING_IT) {
doSomethingElse();
}
// else, you neither handle or track that key
return handled;
}
精彩评论