Shivam
Shivam

Reputation: 145

How to set a different toolbar and hide previous toolbar in fragment

I am trying to inflate different toolbars in my fragments. Although I am able to inflate different toolbars for different fragments the problem is with MainActivity toolbar i am unable to hide it I have used

 (activity as AppCompatActivity).supportActionBar?.hide() 

but it only hides the fragment toolbar, not the MainActivity toolbar I Want to hide the MainActivity toolbar.

My code

fragment

class SearchFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {

        val view = inflater.inflate(R.layout.fragment_search, container, false)
        val toolbar = view.findViewById<Toolbar>(R.id.toolbar_search)

        (activity as AppCompatActivity).setSupportActionBar(toolbar)
        setHasOptionsMenu(true)
//        (activity as AppCompatActivity).supportActionBar?.hide()

        return view

    }

Xml

<androidx.coordinatorlayout.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="56dp"
            app:titleTextColor="#000000"
            app:title="MainActivity"
            app:elevation="8dp" />

    </com.google.android.material.appbar.AppBarLayout>
    
</androidx.coordinatorlayout.widget.CoordinatorLayout>

Upvotes: 0

Views: 342

Answers (1)

Shay Kin
Shay Kin

Reputation: 2677

I believe the toolbar of the fragment is the one that hid because you add it on the activity and then you hide it so try to hide before adding the toolbar of the fragment

        val view = inflater.inflate(R.layout.fragment_search, container, false)
        val toolbar = view.findViewById<Toolbar>(R.id.toolbar_search)
        (activity as   AppCompatActivity).supportActionBar?.hide()
        (activity as AppCompatActivity).setSupportActionBar(toolbar)
        setHasOptionsMenu(true) 
         

Upvotes: 1

Related Questions