Search code examples
androidandroid-actionbarandroid-optionsmenu

How to add options menu (either 3 dots and/or action icons) to a tabbed activity?


I started my project with the template "Tabbed Activity" and am now trying to add an options menu. I have done this before with a blank activity and it worked fine. As far as I can tell I have done all the same steps, even as outlined by the documentation: https://developer.android.com/guide/topics/ui/menus#options-menu

When I run the app, nothing shows up. I would expect to see the 3 dots icon. I also tried adding icons to see if they would show up as actions. No luck. Here's what I've got in my MainActivity.java file:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
        ViewPager viewPager = findViewById(R.id.view_pager);
        viewPager.setAdapter(sectionsPagerAdapter);
        TabLayout tabs = findViewById(R.id.tabs);
        tabs.setupWithViewPager(viewPager);
    }

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

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        switch (item.getItemId())
        {
            case R.id.settingsMenuItem:
                ShowSettings();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void ShowSettings() {
        // TODO show settings
    }
}

And this is the options menu xml file which is "options_menu_layout.xml" located in the res/menu directory:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/settingsMenuItem"
        android:icon="@drawable/baseline_settings_black_48"
        android:title="@string/menu_option_settings"/>
</menu>

This seems to work on a blank activity, but not in this tabbed activity. Is there something I'm missing that is required to make these compatible?


Solution

  • Turns out when using the template "Tabbed Activity" the manifest file uses a "NoActionBar" version of the theme. I deleted the last part of this line:

    android:theme="@style/Theme.ExampleApp.NoActionBar">
    

    So it is this instead:

    android:theme="@style/Theme.ExampleApp">