I'm trying to find way to achieve such effect https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0B6Okdz75tqQsVlhxNGJCNTEzNFU/components-buttons-fab-behavior_04_xhdpi_009.webm
I'm using android.support.v4.view.ViewPager
I appreciate any hints and help
Here is another solution. The problem for me with other ones is that giving the control of the FAB to the activity that contains the ViewPager makes thing difficult to code.
I need lots of controls on the FAB by the Fragments to easily change the FAB icon and set specific listeners on it.
Roughly, the steps are:
public void shareFab(FloatingActionButton sharedFab)
; inside this method, each fragment will set the FAB icon and add the needed listenersViewPager.OnPageChangeListener
listener on the ViewPager that will trigger animations and calls myshareFab
methods.So each time a fragment is displayed, the containing activity will give to the displayed fragment the reference of the FAB. The fragment then reset/recycle the FAB to suit its needs.
Here is an example:
The fragments to display
The container activity
... and the classical layout of the main activity
The pros are:
The cons are:
The solution that I discovered was:
My fragments that are shown within my ViewPager implement an Interface (in my case
FloatingActionButtonFragment
). This interface requires that the fragment have a methodhandleFABClick(View)
.My ViewPager change listener then looks like below:
This makes the FAB 'hide' when the user is changing views, but then triggers the show method when the view state is either idle (it has settled) or is settling (I needed to do both as it didn't feel right only using idle).
For my problem, I did not want to show floating action button on first Tab; in order to achieve this I added
in floating action bar.
And I have added ViewpagerListner in my activity as suggested by @chantell
I recently found much better solution that i am satisfied with. FAB hide method can also have a parameter - listener which is triggered when the button is hidden (show method also have this). The only drawback is that you have to implement viewpager and tablayout changes manually.
If you want to show FAB only on specific tabs, you can change the onTabSelected method to:
For good animation of hide and show use this :
First, you need to have the layout with the floating action button anchored to the ViewPager:
Now that you have the FAB anchored to the ViewPager (note: I've tried this on a fragment that is a tab in the viewpager; it does not seem to behave properly), add an OnPageChangeListener to your ViewPager like so:
The animations for the "pop" and the "shrink" upon switching tabs are handled automatically for you with the new version of the Support Library.