I have a Fragment which has a ViewPager
and BottomAppBar
. ViewPager
is showing 3 fragments, each fragment has it's own FloatingActionButton
(as I am using Navigation Component, in my case each fragment is a container of navigation graph).
Each time the user is swiping the ViewPager
I want to show the fragment and also I want to attach the FloatingActionButton
to the BottomAppBar
. The problem is that Fragments does not know anything about BottomAppBar
as they are in separate modules. What is the best way to do this?
This answer is in 2 parts and there are a number of ways of doing it.
First you need to know when each Fragment is shown to then trigger the Fab to change.
This can be done via 2 method, either use the changes in the Fragment's lifecycle to trigger this change or with a PageChangeListener.
With the current version of Viewpager you can use BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
https://developer.android.com/reference/androidx/fragment/app/FragmentStatePagerAdapter#FragmentStatePagerAdapter(androidx.fragment.app.FragmentManager,%20int)
The onResume
method of the Fragment is called when it becomes the primary item (the one shown on screen), this can then be used to trigger the Fab change.
The alternate is to add a PageChangeListener and onPageSelected(int)
method https://developer.android.com/reference/androidx/viewpager/widget/ViewPager#addOnPageChangeListener(androidx.viewpager.widget.ViewPager.OnPageChangeListener)
The second part, depending which option chosen and the structure of the project you will probably need to communicate that change between components/fragments.
This can be done a number of ways, most common are interfaces or shared viewmodel.
More details of inter Fragment(component) at https://androidwave.com/passing-data-between-fragments/
e.g.
The activity or possibly the BottomAppBar implements an interface the each Fragment can call to say it is the primary Fragment
Or the BottomAppBar observes the shared viewmodel value that defines which Fragment in on screen and each Fragment updates the share viewmodel value with it's number when it is the primary Fragment,