Asked 7 years ago
24 Jan 2017
Views 928
ajamil

ajamil posted

How to display menu item in action bar in android ?

How to display menu item in action bar in android ?
lain

lain
answered Apr 24 '23 00:00

To display a menu item in the action bar in an Android app, you can follow these steps:

1.Create a new menu resource file. Right-click on the "res" folder in your project and select "New > Android Resource File". Choose "menu" as the resource type, give it a name like "menu_main", and click "OK".

2.Open the newly created file and add a menu item. For example, you can add a "Settings" item like this:



<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:icon="@drawable/ic_settings"
        android:showAsAction="ifRoom" />
</menu>

In this example, the android:showAsAction="ifRoom" attribute specifies that the item should be shown as an action in the action bar if there is enough room for it. The android:icon attribute specifies the icon to use for the menu item.

3.In your activity, override the onCreateOptionsMenu() method to inflate the menu resource file:


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

This method is called when the activity is first created, and you can use it to specify the options menu for the activity. The [b] getMenuInflater().inflate() [/b] method inflates the menu resource file and adds it to the activity's menu.

4.If you want to handle clicks on the menu item, override the onOptionsItemSelected() method:


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_settings) {
        // Handle the settings item click
        return true;
    }

    return super.onOptionsItemSelected(item);
}

In this example, we check if the clicked item has the ID of our "Settings" item and handle it accordingly. You can add more items to the menu and handle them in a similar way.

That's it! When you run your app, you should see the menu item displayed in the action bar (or in the overflow menu if there isn't enough room for it).




Post Answer