Rahul Saxena Rahul Saxena - 4 months ago 20
Android Question

How to add night mode and day mode in android actionbar

I am developing an android application. I want to add night mode and day mode in app. I want to make it visible in app's actionbar.

Currently my style.xml file is

<style name="Theme.FullScreen" parent="@android:style/Theme.Black.NoTitleBar.Fullscreen"></style>

<style name="PreferencesTheme" parent="android:Theme.Light">
<item name="android:background">#FFEAEAEA</item>
</style>

<style name="PreferencesTheme" parent="android:Theme.Light">
<item name="android:windowBackground">@drawable/ic_icon_settings</item>
</style>

Answer

I solved this problem by using this in my xml file :

    <style name="ActionBar" parent="@android:style/Widget.Holo.ActionBar" />

    <style name="ActionBar.Light" parent="@style/ActionBar">
        <item name="android:background">@color/actionbar_background_light</item>
    </style>

    <style name="ActionBar.Dark" parent="@style/ActionBar">
        <item name="android:background">@color/actionbar_background_dark</item>
    </style>

    <style name="AppTheme.Light" parent="@android:style/Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/ActionBar.Light</item>
        <item name="android:windowActionBarOverlay">true</item>
        <item name="listDragShadowBackground">@android:color/background_light</item>
        <item name="menuIconCamera">@drawable/ic_menu_camera_holo_light</item>
        <item name="menuIconToggle">@drawable/ic_menu_toggle_holo_light</item>
        <item name="menuIconShare">@drawable/ic_menu_share_holo_light</item>
    </style>

    <style name="AppTheme.Dark" parent="@android:style/Theme.Holo">
        <item name="android:actionBarStyle">@style/ActionBar.Dark</item>
        <item name="android:windowActionBarOverlay">true</item>
        <item name="listDragShadowBackground">@android:color/background_dark</item>
        <item name="menuIconCamera">@drawable/ic_menu_camera_holo_dark</item>
        <item name="menuIconToggle">@drawable/ic_menu_toggle_holo_dark</item>
        <item name="menuIconShare">@drawable/ic_menu_share_holo_dark</item>
    </style>

MENUS TO SWITCH BETWEEN THE MODES

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

    case R.id.toggleTheme:
        if (mThemeId == R.style.AppTheme_Dark) {
            mThemeId = R.style.AppTheme_Light;
        } else {
            mThemeId = R.style.AppTheme_Dark;
        }
        this.recreate();
        return true;

    default:
        return super.onOptionsItemSelected(item);
    }
}

The Global Variable necessary for switching between the modes:

    private int mThemeId = -1;

And for saving the last selected mode, in the onCreate():

    if(savedInstanceState != null && savedInstanceState.getInt("theme", -1) != -1) {
        mThemeId = savedInstanceState.getInt("theme");
        this.setTheme(mThemeId);
    }