how to set collapsing toolbar if I use single activity and navigation component?

Viewed 215

so I use navigation component and single activity. I set my toolbar in my MainActivity, using this code

    val navController = Navigation.findNavController(this,R.id.nav_host_fragment)

    val appBarConfiguration = AppBarConfiguration(setOf(
        R.id.destination_home,
        R.id.destination_search,
        R.id.destination_user_control,
        R.id.destination_create_event,
        R.id.destination_inbox,
      )
    )

    toolbar.setupWithNavController(navController,appBarConfiguration)

and now, I need to implement collapsing toolbar in one of the fragment. but the problem is, I need to set the toolbar in XML inside CollapsingToolbarLayout

but the toolbar xml that I have is located in MainActivity.xml

should I place the collapsing toolbar in my MainActivity ? if so then it affect all my fragment right ? I am confused what should I do ?

1 Answers

Disclaimer: I'm a begginer too, not sure if this is the right approach, but worked for me.

I solved this by setting CollapsingToolbarLayout's app:toolbarId property to the same id the MainActivity's toolbar has.

  1. MainActivity has this structure:

DrawerLayout

-> LinearLayout

--> toolbar (id = myToolbar)

--> fragment

-> NavigationView

  1. Fragment which needs collapsable content:

CoordinatorLayout

-> Appbarlayout

--> CollapsingToolbarLayout (this is the key, setting app:toolbarId property to the same id as in MainActivity 'myToolbar')

---> collapsable content, what ever you want

-> rest of the layout

Related