Option menu
- To implement Option menu we have to add new folder in res/directory name menu.xml.
2. Copy the code into the new menu.xml file
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/icon"
android:icon="@drawable/icon" />
<item android:id="@+id/text"
android:title="Text" />
<item android:id="@+id/icontext"
android:title="Icon and text"
android:icon="@drawable/icon" />
</menu>
3. Then change the main activity as follows:
public class SimpleOptionMenuActivity extends Activity {
/** Called when the activity is first created. */
@Override
public boolean onCreateOptionsMenu(Menu menu) //here specify the xml file defined by menu.xml
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
On line 2 you see the parameter menu. In this menu we will inflate our own menu defined by our menu.xml.
On line 3 we get the MenuInflater from the Activity class. We need this MenuInflater object to inflate, or merge, our own menu in the menu given as a parameter on line 2.
Line 4 inflate the given menu with our own menu. Line 5 is just our return type.
4. To implement a reaction of our menu, we should override another method onOptionItemSelected().
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.icon: Toast.makeText(this, "You pressed the icon!", Toast.LENGTH_LONG).show();
break;
case R.id.text: Toast.makeText(this, "You pressed the text!", Toast.LENGTH_LONG).show();
break;
case R.id.icontext: Toast.makeText(this,"You pressed the icon and text!", Toast.LENGTH_LONG).show();
break;
}
return true;
}
No comments :
Post a Comment