Search code examples
androidmaterial-designandroid-statusbar

Android set Normal status bar programmatically


I've been working with Material design and CollapsingToolbarLayout and want to use Translucent Status Bar in one of the fragments. I have MainActivity with AppTheme (in style.xml translucent status bar and overlaying are false). I have Fragment1 and Fragment2 Fragment1 is not supposed to have Translucent Status Bar. Just normal with primaryDarkColor. However, in Fragment2 I need to turn on Translucent Status Bar progromatically. I've achieved it by this way:

   @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //Making status bar transparent
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Window w = getActivity().getWindow(); // in Activity's onCreate() for instance
        w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    }

And when I go back to Fragment1 again, Status Bar is hidden. I guess I should disable Translucent Status Bar onPause() or in onStop(). But dont know how to do it progromatically. Any suggestions?


Solution

  • To change status bar color use setStatusBarColor(int color).use below code

    Window window = activity.getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    window.setStatusBarColor(activity.getResources().getColor(R.color.example_color));