How do I set the intent of menu items defined in an Android menu xml file?
How do I set the intent of menu items defined in an Android menu xml file? For example I currently have...
<menu xmlns:android="http://schemas.android.com/apk/res/android" android:name="Main Menu">
<item android:title="@string/resume_game" android:icon="@drawable/resume"></item>
<item android:title="@string/play_golf" android:icon="@drawable/play_golf"></item>
<item android:title="@string/my_rounds" android:icon="@drawable/my_rounds"></item>
</menu>
And i开发者_开发知识库n my Activity I have the following method overriden...
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main_menu, menu);
final MenuItem menuItem = (MenuItem) menu.findItem(R.id.about_item);
return true;
}
What synic says is true, and that approach does allow you to respond to a menu item being selected, I don't believe that answers the question, which is how to set the intent of a menu item defined in an XML file.
That being said, the question confuses me, because it should be obvious that you simply call menuItem.setIntent() on the indicated menu item:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main_menu, menu);
final MenuItem menuItem = (MenuItem) menu.findItem(R.id.about_item);
menuItem.setIntent(myIntent);
return true;
}
If Benju doesn't know how to create intents and thinks that intents are the only way to respond to menu items, then synic's answer is spot-on.
Give each of your menu items an id, such as android:id="@+id/resume_game", and then you can define the onOptionItemsSelected() method:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.resume_game:
resumeGame();
return true;
case R.id.play_golf:
playGolf();
return true;
}
return super.onOptionsItemSelected(item);
}
精彩评论