转载请注明出处:http://blog.csdn.net/droyon/article/details/9427651
实现思路:通过更换主题来实现应用程序内部换肤。
setTheme(getPersistStyle());
源代码下载
程序运行效果:
默认主题:
主题一
主题2
主题三
主题更换预览界面
在应用程序内部定义一套需要更换资源(背景图片,按钮图片,按钮文字等)的属性,通过样式(style)来给属性赋值。
关键代码:
属性资源:
attr.xml
<?xml version="1.0" encoding="utf-8"?> <resources xmlns:hlwang="http://schemas.android.com/apk/res/com.example.androidtest"> <declare-styleable name="ResourceStyle"> <attr name="activity_background"/> <attr name="activity_button_show" /> <attr name="activity_button_show_text" /> </declare-styleable> <attr name="activity_background" format="reference"></attr> <attr name="activity_button_show" format="reference"></attr> <attr name="activity_button_show_text" format="string"></attr> <attr name="activity_button_switcher_normal" format="reference"></attr> <attr name="activity_button_switcher_pressed" format="reference"></attr> </resources>
<resources xmlns:hlwang="http://schemas.android.com/apk/res/com.example.androidtest" xmlns:android="http://schemas.android.com/apk/res/android"> <style name="ResourceStyle"> <item name="activity_background">@android:drawable/screen_background_dark</item> <item name="activity_button_show">@android:drawable/gallery_thumb</item> <item name="activity_button_show_text">@string/button_show_style0</item> </style> <style name="ResourceStyle.r1" parent="@style/ResourceStyle"> <item name="activity_background">@drawable/bj1</item> <item name="activity_button_show">@drawable/btn1</item> <item name="activity_button_show_text">@string/button_show_style1</item> </style> <style name="ResourceStyle.r2" parent="@style/ResourceStyle"> <item name="activity_background">@drawable/bj2</item> <item name="activity_button_show">@drawable/btn2</item> <item name="activity_button_show_text">@string/button_show_style2</item> </style> <style name="ResourceStyle.r3" parent="@style/ResourceStyle"> <item name="activity_background">@drawable/bj3</item> <item name="activity_button_show">@drawable/btn3</item> <item name="activity_button_show_text">@string/button_show_style3</item> </style> </resources>
MainActivity.java
private static final String sStyleKey = "StyleKey"; private static final int sDefaultValue = R.style.ResourceStyle;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = MainActivity.this;
setTheme(getPersistStyle());
setContentView(R.layout.main);
.......
}
private int getPersistStyle(){ SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext); return mSharedPreferences.getInt(sStyleKey, sDefaultValue); }在每一次应用主题之后,执行Activity 的 reCreate
recreate();
总结:这种方式能够实现在应用程序内部进行换肤,定义属性以及Style的目的在于保证程序代码的规范与“整洁”。