Hide/Show Action Bar Menu Items for Certain Fragments in Android

When your app consists of many modules and each module contains several fragments, you will need to hide or show menu items depending on the showing fragments.

Layout

Each module’s menu items should be put in a group for easy access. All groups’ visible states are set to false by default. Then we will set each group’s visibility to true on respective module’s fragments.

<?xml version="1.0" encoding="utf-8"?>
<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=".MainActivity">

    <item
        android:id="@+id/action_home"
        android:icon="@mipmap/ic_home"
        android:orderInCategory="0"
        android:title="@string/action_home"
        app:showAsAction="ifRoom" />

    <group android:id="@+id/group_products"
        android:visible="false">
        <item
            android:id="@+id/action_products"
            android:title="@string/action_products"
            app:showAsAction="never" />
        <item
            android:id="@+id/action_create_product"
            android:title="@string/action_create_product"
            app:showAsAction="never" />
    </group>
</menu>

Fragment

First of all, we need to have this line setHasOptionsMenu(true) to enable menu modification in a fragment.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setHasOptionsMenu(true)
}

Then we show whole group’s menu items on onCreateOptionsMenu event.

override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
    //enable submenu
    menu.setGroupVisible(R.id.group_products, true)
    super.onCreateOptionsMenu(menu, inflater)
}

Leave a Comment

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


Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close