Wednesday, 30 January 2013

Add an "Add" Menu Option | Android Tutorial pdf

Add an "Add" Menu Option

We have most of the logic in place to edit existing restaurants. However, we still need to add a menu item for adding a new restaurant.
To do this, change LunchList/res/menu/option.xml to replace the existing options with one for add:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/add"
android:title="Add"
android:icon="@drawable/ic_menu_add"
/>
</menu>

Note that the add menu item references an icon supplied by Android. You can find a copy of this icon in your Android SDK. Go to the directory where you installed the SDK, and go into the platforms/ directory inside of it.
Then, go into the directory for some version of Android (e.g., android-8/), and into data/res/drawable-mdpi/.Y ou will find ic_menu_add.png in there. Now that we have the menu option, we need to adjust our menu handling to match. Restore our older implementation of onCreateOptionMenu() to LunchList:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.option, menu);
return(super.onCreateOptionsMenu(menu));
}

Then, add an onOptionsItemSelected() implementation in LunchList with the following:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.add) {
startActivity(new Intent(LunchList.this, DetailForm.class));
return(true);
}
return(super.onOptionsItemSelected(item));
}

Here, we launch the DetailForm activity without our "extra", signalling to DetailForm that it is to add a new restaurant.Y ou will need imports again for android.view.Menu, android.view.MenuInflater, and android.view.MenuItem.

No comments: