Android App Bar Tutorials

In its most basic form, the action bar displays the title for the activity on one side and an overflow menu on the other. Even in this simple form, the app bar provides useful information to the users, and helps to give Android apps a consistent look and feel.

Hide/Show Action Bar menu items for different fragments

Menu xml file

<?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_books"
        android:visible="false">
        <item
            android:id="@+id/action_books"
            android:title="@string/books"
            app:showAsAction="never" />
        <item
            android:id="@+id/action_create_book"
            android:title="@string/create_book"
            app:showAsAction="never" />
    </group>
    <group android:id="@+id/group_publishers"
        android:visible="false">
        <item
            android:id="@+id/action_publishers"
            android:title="@string/publishers"
            app:showAsAction="never" />
        <item
            android:id="@+id/action_publisher"
            android:title="@string/publisher"
            app:showAsAction="never" />
    </group>
</menu>

Book fragment

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

override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {    
    menu.setGroupVisible(R.id.group_books, true)
    super.onCreateOptionsMenu(menu, inflater)
}

Publisher fragment

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

override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {    
    menu.setGroupVisible(R.id.group_publishers, true)
    super.onCreateOptionsMenu(menu, inflater)
}

Leave a Comment

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

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