Nick Cardoso Nick Cardoso - 1 month ago 9x
Android Question

Can I anchor nested FloatingActionButton to the viewport?

I have a layout which is nested as follows (I'm using pseudocode and skipping some tags for brevity)

Activity Layout:

- AppBarLayout
- FragmentOne
- FragmentTwo

Fragment two layout uses AppBarLayout.ScrollingViewBehavior but contains a FAB:

- FloatingActionButton
- TabLayout

So the Runtime hierarchy looks like

CoOrdinatorLayout (Activity)
- AppBarLayout
- LinearLayout (FragmentOne)
- CoOrdinatorLayout (FragmentTwo)
- FloatingActionButton
- TabLayout

The FAB should be anchored to the bottom right of the viewport (physical screen) but instead (because of the behaviour) is at the bottom right of the viewpager (which contains lists on each page).
This means the FAB is only visible when the layout is scrolled to the end (and the App Bar Layout is collapsed)

Is there some way I can make the FAB anchored to the viewport while it is nested like this? Moving it to the activity is not a good option

Edit - It's been a few days so I've added the solution I used below, however if someone can suggest a cleaner, working XML-based solution I will change the accepted answer as that is what I am after


The solution I used was to Programmaticaly create the FAB inside the Fragment (so the fragment is still the one correctly responsible for implementing it's listeners etc.) and then attach it to the Activity's CoOrdinator layout (which I found using a getter interface on the activity because it seems like the cleaner alternative to using getActivity().findViewById(...))

public class MyActivity extends implements MyCallbacks {

public interface MyCallbacks {
    CoordinatorLayout getCoordinatorLayoutRoot();

public class MyFragment extends Fragment {


    private void setupNewFab() {
        final CoordinatorLayout rootCoordinator = ((MyCallbacks) getActivity())
        final LayoutInflater inflater = (LayoutInflater) getActivity()
        final FloatingActionButton fab = (FloatingActionButton) inflater.inflate(
            R.layout.my_fab_definition, rootCoordinator, false);
        fab.setOnClickListener(v -> myAction());


One thing to note is that I used this inflation approach as setting the click listener on the result of View.inflate(...) didn't appear to work