现在的位置: 首页 > 综合 > 正文

Android4: 动态切换界面风格

2013年03月24日 ⁄ 综合 ⁄ 共 1067字 ⁄ 字号 评论关闭

Theme.Light:

Theme.Dark:

1. styles.xml定义两套theme

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme.Light" parent="@android:style/Theme.Holo.Light">
        <item name="menuIconToggleTitle">@drawable/ic_menu_toggle_title_holo_light</item>
        <item name="menuIconToggleTheme">@drawable/ic_menu_toggle_theme_holo_light</item>
    </style>
    <style name="AppTheme.Dark" parent="@android:style/Theme.Holo">
        <item name="menuIconToggleTitle">@drawable/ic_menu_toggle_title_holo_dark</item>
        <item name="menuIconToggleTheme">@drawable/ic_menu_toggle_theme_holo_dark</item>
    </style>        
</resources>

2. 点击Day/Night时

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

3. theme id 保存为savedInstanceState

    @Override
    public void onSaveInstanceState (Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("theme", mThemeId);
    }

4. onCreate中根据theme id 加载theme

        if(savedInstanceState != null) {

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

【上篇】
【下篇】

抱歉!评论已关闭.