Create new project having:
Application Name : AndroidMenu
Project Name : AndroidMenu
Package Name : com.codingredefined.androidmenu
Click NEXT
Click NEXTYou may change the icon of your app then click NEXT
Click NEXT
Click NEXT
You may or may not change the code of the layout file as it has nothing to do with this example.
For those who want to change:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Android Menu Item" />
Now to create the menu items, goto menu file in the menu folder again in res folder and paste the following code:
<item
android:id="@+id/item_1"
android:orderInCategory="100"
android:showAsAction="never"
android:title="item 1"/>
<item
android:id="@+id/item_2"
android:orderInCategory="100"
android:showAsAction="never"
android:title="item 2"/>
Then in order to make the menu items working use the below code after the onCreate()
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case R.id.item_1:
Toast.makeText(this,"Menu Item 1",Toast.LENGTH_SHORT).show();
break;
case R.id.item_2:
Toast.makeText(this,"Menu Item 2",Toast.LENGTH_SHORT).show();
break;
default:
break;
}
return true;
}
Pasting the above code will produce a toast on your emulator screen as shown in below figures.
After pasting the code run your application and observe the output.










No comments:
Post a Comment