Search code examples
javaandroidandroid-fragmentsappbar

Change AppBar's icons depending on the Context (Fragments)


I have my AppBar on my MainActivity. My MainActivity has a layout which works like a container of fragments.

What I want to accomplish is that I want my AppBar icons to change depending on which Fragment's on top at the moment.

something like this:

switch (item.getItemId()){
    case R.id.semanario:
        fragmentTransaction.replace(R.id.viewPagerMainContenedor, new FragmentSemanario());
        fragmentTransaction.addToBackStack(null).commit();
        myToolbar.SETICON(R.drawable.iconExample) (And how to change the xml atributte "app:showAsAction = always)
        break;

I thought about making an AppBar for each fragment but it should be easier than that, isn't it?


Solution

  • Add a method inside your main activity something like below :

    updateToolbar(int title, int drawable){
     toolbar.setTitle(title);
     toolbar.setIcon(drawable);
    }
    

    and then call this method from your fragment :

    getActivity().updateToolbar(title,R.drawable.icon);
    

    To change action overflow icon :

    <style name="AppTheme.Base" parent="Theme.AppCompat.Light">
    <item name="actionOverflowButtonStyle">@style/OverFlow</item>
    </style>
    
    <style name="OverFlow" 
    parent="Widget.AppCompat.ActionButton.Overflow">
    <item name="android:src">@drawable/my_overflow_menu</item>
    </style>
    

    For other custom icons you can simply update through thier views. Hope it helps.