0

I have one MainActivity with FrameLayout and BottomNavigationView. Based on BottomNavigationView selected item I load fragments inside FragmeLayout. I have three fragments, call them A,B,C. For each of them I have defined layout xml file. For fragments A and B I don't have a toolbar but for fragment C I have defined in fragment_c.xml Toolbar( androidx.appcompat.widget.Toolbar).

  • I defined menu_c.xml file with one item,
  • I have added this line in Fragment_C.java setHasOptionsMenu(true) in onCreateView method,
  • I have also added inflater.inflate(R.menu.menu_c.xml, menu) in onCreateOptionsMenu method

Problem is that the menu does not apper in Fragment_C, toolbar is there but menu isn't. I have searched for answers and couldn't find working solution. I found that for regular toolbar with options you need to call setSupportActionBar(actionBarToolBar) from onCreate in your main activity, but I do not want toolbar to exist through all 3 fragment, I only want toolbar in my third fragment. I do not want to hide/show toolbar with options, Is there a way to make this work with toolbar with options in only one fragment

Alen
  • 949
  • 3
  • 17
  • 37
  • Possible duplicate of [how to use setSupportActionBar in fragment](https://stackoverflow.com/questions/38189198/how-to-use-setsupportactionbar-in-fragment) – Bö macht Blau Aug 14 '19 at 17:39

1 Answers1

0

First create toolbar.xml

<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

Then in fragmentC.xml include the layout toolbar

 <include layout="@layout/toolbar" />

, thus you can call inside your fragmentC.kt inside onViewCreated() use this line

  toolbar.inflateMenu(R.menu.menu_c)
EliodeBeirut
  • 74
  • 1
  • 13