0

I have a layout with bottonNavigationView and fragments. How can I have different toolbar menus for each fragment? I've already tried several things.

In a fragment, I hace used.

((AppCompatActivity) getActivity()).getSupportActionBar()

This is the layout of a fragment

<FrameLayout 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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.cspm.ventas6.cspm.v_fragments.f_clientes"
    android:focusable="false">

    <LinearLayout
        android:id="@+id/con_listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:descendantFocusability="blocksDescendants"
        android:focusable="false">

  <android.support.design.widget.AppBarLayout
        android:id="@+id/appBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar">

        <!-- Toolbar is the actual app bar with text and the action items -->
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways" />
    </android.support.design.widget.AppBarLayout>

        <ListView
            android:id="@+id/client_list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:divider="@null" />
    </LinearLayout>
</FrameLayout>

1 Answers1

0

In your fragment, add following two methods.

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // tells the fragment that fragment will use toolbar's options menu
    setHasOptionsMenu(true);
}

/**
* this method is called when fragment prepares options menu, 
* simply, inflate your menu and call super
*/
@Override
public void onPrepareOptionsMenu(Menu menu) {
    getActivity().getMenuInflater().inflate(R.menu.menu_res_id, menu);
    super.onPrepareOptionsMenu(menu);
}

Change menu_res_id with your menu resource.

And, if you only want to remove an item from current menu, then replace line

getActivity().getMenuInflater().inflate(R.menu.menu_res_id, menu);

with

menu.findItem(R.id.action_search).setVisible(false);
rupinderjeet
  • 2,984
  • 30
  • 54