Inside the detail fragment, I want to implement the AppBarLayout. But I have already a Toolbar on activity level.
So, now the activity has a toolbar, and you want to set another toolBar in the DetailFragment
. And as you're using navigation components, you are likely making the toolbar managed by the navController
Well, this requires you to move the activity level toolBar to be in the main fragment; that is hosted by navHostFragment
.
The reason: because setting another toolbar from the fragment level will duplicate it as the activity level toolbar always persist. Check this answer for that.
And therefore you need to setup the toolBar in the fragments instead; and normally when you move from a fragment to another though the navigation components, no duplication will occur, and now you can have different toolbar as you'd like to.
Here is a schematic demo:
Activity:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun setupActionBar(toolbar: Toolbar) {
setSupportActionBar(toolbar)
val navHostFragment =
supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
val appBarConfiguration = AppBarConfiguration.Builder(
R.id.fragment, R.id.fragment_b
) .build()
NavigationUI.setupActionBarWithNavController(
this,
mNavController,
navController
)
}
}
FragmentA
class FragmentA : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_a, container, false)
(requireActivity() as MainActivity).setupActionBar(view.findViewById(R.id.fragment_toolbar))
return view
}
}
FragmentB: Similar to FragmentA, but has its own toolBar
class FragmentB : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_b, container, false)
(requireActivity() as MainActivity).setupActionBar(view.findViewById(R.id.fragment_toolbar))
return view
}
}