Search code examples
javaandroidandroid-fragmentsfloating-action-buttonandroid-architecture-components

Assign different actions to a Floating Button on Android


I have an application under construction using the Navigation Drawer Activity which is the one with the left menu like the old version of Google PlayStore:

enter image description here

As you know the design comes bundled with a FAB (FloatingActionButton):

enter image description here

Now, in the left side menu you see these three Fragments:

enter image description here

I wanted to know, how do I assign different actions to the FAB when I change the Fragment? From the MainActivity I see that there is the k but I do not understand how to assign a different functionality to it, since when changing the Fragment, the same FAB is still there and executes the same action that in this case is a Toast:

 binding.appBarMain.fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Toast.makeText(MainActivity.this, "Home Fragmen Visualizado", Toast.LENGTH_SHORT).show();
    }
});

The idea is, if someone can explain or tell me how I control the FAB action according to the Fragment it is in.


Solution

  • You can get the current fragment hosted by the NavHostFragment and decide what you need to do then with the fab.

    binding.appBarMain.fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
    
            final NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment); // change `nav_host_fragment` according to yours 
    
            if (navHostFragment != null) {
                Fragment currentFragment = navHostFragment.getChildFragmentManager().getFragments().get(0);
    
                if (currentFragment instanceof HomeFragment) {
                    Toast.makeText(MainActivity.this, "Home Fragment", Toast.LENGTH_SHORT).show();
    
                } else if (currentFragment instanceof SlideshowFragment) {
                    Toast.makeText(MainActivity.this, "Slideshow Fragment", Toast.LENGTH_SHORT).show();
    
                } else if (currentFragment instanceof GalleryFragment) {
                    Toast.makeText(MainActivity.this, "Gallery Fragment", Toast.LENGTH_SHORT).show();
                }
            }
    
        }
    });
    

    Also you can remove this fab, and put a fab in each fragment (HomeFragment, GalleryFragment, & SlidshowFragment) to be manipulated individually.