Start PreferenceActivity with menu button and finish with back button
I've modify a prefenceActivity application of CommonsWare but ran into a problem.
I would like to start a prefenceActivity with the menu button and just finish it with the back button.
I've got this to start my prefenceActivity via the menu button:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
startActivity(new Intent(this, EditPreferences.class));
return(true);
}
And it does go back to my main view of the app, but it isn't finished I think, because when I press the menu button again the prefenceActivity doesn't pop up agian. I have to close my app and than it works again only for 1 t开发者_如何学JAVAime only.
I've already tried to finish it in my prefenceActivity when I press the back button but this didn't help either.
What is it that i'm doing wrong?
Thanks for your help!
If you just want to do something when the menu button is pressed, you should simply implement onKeyDown()/onKeyUp() to handle the menu key like you would any other key. Be sure to return true to say you are consuming it so the default key handling is not executed (generally involving showing the menu panel).
Do NOT do this by implementing onCreateOptionsMenu() or onPrepareOptionsMenu(). These are hooks you implement to interact with the options menu, NOT with the menu key. There is no guarantee that these will be called in any relationship with the menu key being pressed. It happens that often they are, but there is nothing defined in the API saying this is so and indeed this explicitly is not the case.
As a general rule, relying on side-effects like this (oh when the user presses the menu key this API that is not documented as being directly tied to the menu key is invokved) is something you absolutely should avoid. You are by definition relying on implementation details, and there is a good chance this will bite you.
For example as of Android 3.0 when there is an action bar onCreateOptionsMenu() is called immediately when the activity is created and onPrepareOptionsMenu() is called whenever the actions in the action bar need to be updated. This is because the options menu is now integrated with the action bar.
A quick solution (though I don't suggest it) is to use
public boolean onPrepareOptionsMenu (Menu menu)
This is called everytime the menu button is pressed, right before the menu is shown. The problem with onCreateOptionsMenu is it is only called before the first time the Menu is created. So this isn't so much that the activity isn't finishing, but a problem with the method you used to start the activity
精彩评论