Robert Buckley February 2016

My app has an action bar, but no menu.xml. How do I modify my action bar?

Hello and thanks for reading,

When I first made my project, I was prompted by Android Studio to chose a boiler plate. I chose empty activity (the one without FAB and others). Still, my app has an ActionBar, but it just shows the name. Now, I want to modify that action bar and add a menu. My java extends AppCompatActivity, so there is an action bar. However, unlike my prior experiences in eclipse, there is no menu xml to that I can locate.

How can I add one or modify my action by through other means? Can I add one manually?

Thanks!

Answers


Rami February 2016

1) You need to create (or modify if it exist) your menu resources file, /res/menu/main_menu.xml to create the actions.

eg:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/action_refresh"
        android:showAsAction="always"
        android:icon="@drawable/ic_action_refresh"
        android:title="Refresh"/>
    <item
        android:id="@+id/action_settings"
        android:showAsAction="always"
        android:icon="@drawable/ic_action_setting"
        android:title="Settings">
    </item>

</menu> 

2) Override onCreateOptionsMenu() in your activity to allows to inflate actions defined in your XML:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_menu, menu);
    return true;
} 

3) Override onOptionsItemSelected() to react the actions selection:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

    case R.id.action_refresh:
      Toast.makeText(this, "Refresh selected", Toast.LENGTH_SHORT).show();
      break;

    case R.id.action_settings:
      Toast.makeText(this, "Settings selected", Toast.LENGTH_SHORT).show();
      break;
    }

    return true;
}

Post Status

Asked in February 2016
Viewed 2,282 times
Voted 7
Answered 1 times

Search




Leave an answer