1

How can I define a different Statusbar and Actionbar color for each fragment ?

At the moment.

enter image description here

How it should look.

enter image description here

enter image description here

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
xXElsterXx
  • 39
  • 1
  • 1
  • 10
  • http://stackoverflow.com/q/2482848/1168654 – Dhaval Parmar Feb 11 '16 at 18:54
  • Have a look at `Toolbar` it is much more flexible than old actionbar that is hardcoded in activity UI – CROSP Feb 11 '16 at 18:55
  • 1
    You need only to change backgound of `ActionBar` ? Have you tried to use `ActionBar bar = getActionBar(); bar.setBackgroundDrawable(new ColorDrawable("COLOR")); ` – CROSP Feb 11 '16 at 19:08
  • @CROSP yes, but **getActionBar()** doesn't work in my fragment. – xXElsterXx Feb 12 '16 at 16:05
  • Of course it will not work in `Fragment` use something like this `getActivity().getActionBar()` I will post the answer explaining how implement this better ok ? – CROSP Feb 12 '16 at 16:17

1 Answers1

1

First of all, I would highly recommend you to migrate to new approach - Toolbar. It is much more flexible and you can customize it as plain View.

About your question.
You can just get ActionBar object and setBackground programatically.
Here is short example
ActionBar bar = getActionBar(); bar.setBackgroundDrawable(new ColorDrawable("COLOR IN HEX 0xFFFF6666 for instance"));

I will show how would I implement this. This is more about architecture and patterns.

Use some base class for Fragment it would be better to have base class for Activity as well. Lets consider

public class BaseFragment extends Fragment

And you Activity class in which your fragment lives.

public class MainActivity extends Activity

And you have to define responsibilities of Activity in this case and create interfaces

In your case to work with ActionBar

Create interface

public interface ActionBarProvider {
  void setActionBarColor(ColorDrawable color);
}

Make your activity implement this interface

public class MainActivity extends Activity implements ActionBarProvider {
    public void setActionBarColo(ColorDrawable color) {
      ActionBar bar = getActionBar();
      bar.setBackgroundDrawable(color));
    }
}

And finally in BaseFragment in onAttach

public void onAttach(Context context) {
        super.onAttach(context);
        mActionBarProvider = (ActionBarProvider) context;
}

Make mActionBarProvider variable protected and make each fragment extend BaseFragment and you can change action bar color from any fragment like this mActionBarProvider.setActionBarColor(new ColorDrawable());

Hope this helps.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
CROSP
  • 4,499
  • 4
  • 38
  • 89