Android 4: 动态切换界面风格

Linux大全评论945 views阅读模式

Theme.Light:

Android 4: 动态切换界面风格

Theme.Dark:

Android 4: 动态切换界面风格

1. styles.xml定义两套theme

[html]

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <style name="AppTheme.Light" parent="@Android:style/Theme.Holo.Light">  
  4.         <item name="menuIconToggleTitle">@drawable/ic_menu_toggle_title_holo_light</item>  
  5.         <item name="menuIconToggleTheme">@drawable/ic_menu_toggle_theme_holo_light</item>  
  6.     </style>  
  7.     <style name="AppTheme.Dark" parent="@android:style/Theme.Holo">  
  8.         <item name="menuIconToggleTitle">@drawable/ic_menu_toggle_title_holo_dark</item>  
  9.         <item name="menuIconToggleTheme">@drawable/ic_menu_toggle_theme_holo_dark</item>  
  10.     </style>          
  11. </resources>  

2. 点击Day/Night时

[html]

  1. case R.id.menu_toggleTheme:  
  2.     if (mThemeId == R.style.AppTheme_Dark) {  
  3.         mThemeId = R.style.AppTheme_Light;  
  4.     } else {  
  5.         mThemeId = R.style.AppTheme_Dark;  
  6.     }  
  7.     this.recreate();  
  8.     return true;  

3. theme id 保存为savedInstanceState

[html]

  1. @Override  
  2. public void onSaveInstanceState (Bundle outState) {  
  3.     super.onSaveInstanceState(outState);  
  4.     outState.putInt("theme", mThemeId);  
  5. }  

4. onCreate中根据theme id 加载theme
[html]

  1. if(savedInstanceState != null) {  
  2.   
  3.     if (savedInstanceState.getInt("theme", -1) != -1) {  
  4.       mThemeId = savedInstanceState.getInt("theme");  
  5.       this.setTheme(mThemeId);  
  6.     }  
  7. }  

企鹅博客
  • 本文由 发表于 2019年8月20日 10:51:54
  • 转载请务必保留本文链接:https://www.qieseo.com/174063.html

发表评论