Android menu example

In this tutorial we will learn how to create menus in android. Using Options menu you can give options for different actions inside the activity itself. In this example we will have a menu with three menu items item1,item2,item3.

First step is to have an xml file under res/menu/

menu_main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.codesfor.video.MainActivity">

<item
android:id="@+id/item1"
android:orderInCategory="100"
android:title="item1"
app:showAsAction="never" />

<item
android:id="@+id/item2"
android:orderInCategory="100"
android:title="item2"
app:showAsAction="never" />

<item
android:id="@+id/item3"
android:orderInCategory="100"
android:title="item3"
app:showAsAction="never" />


</menu>

Now simply use the below code in your activity java file.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {

case R.id.item1:

//item 1 click action here
Toast.makeText(getApplicationContext(), " clicked Item 1", Toast.LENGTH_LONG).show();
return true;

case R.id.item2:

//item 1 click action here
Toast.makeText(getApplicationContext()," clicked Item 2",Toast.LENGTH_LONG).show();
return true;

case R.id.item3:

//item 3 action here
Toast.makeText(getApplicationContext()," clicked Item 3",Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}

If you want to show icon in the action bar instead of list menu, change your item in the xml file as follows

<item
android:id="@+id/item1"
android:orderInCategory="100"
android:title="item1"
android:icon="@drawable/your_icon"
android:showAsAction="always"
tools:ignore="AppCompatResource" />

 

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

Add a Comment

Your email address will not be published. Required fields are marked *