主题皮肤切换的简单实现

一个简单的皮肤切换实现

先上效果图:

中间的选择皮肤的Dialog由于录制gif的时候帧被过滤掉了,下面Dialog截图:

实现步骤

一、在styles.xml中定义style皮肤颜色样式

当然在定义前需要在colors.xml中准备好各种皮肤的颜色,下面是一些Material Design中的颜色值:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<color name="material_blue">#2196F3</color>
<color name="material_light_blue">#03A9F4</color>
<color name="material_pink">#E91E63</color>
<color name="material_red">#F44336</color>
<color name="material_purple">#9C27B0</color>
<color name="material_deep_purple">#673AB7</color>
<color name="material_teal">#009688</color>
<color name="material_deep_orange">#FF5722</color>
<color name="material_green">#4CAF50</color>
<color name="material_cyan">#00BCD4</color>
<color name="material_orange">#FF9800</color>
<color name="material_indigo">#3F51B5</color>
<color name="material_brown">#795548</color>
<color name="material_blue_gray">#607D8B</color>
<color name="material_amber">#FFC107</color>
<color name="settings_item_title">#BB000000</color>
<color name="settings_item_desc">#55000000</color>
<color name="dialog_text_color">#99000000</color>

然后在styles.xml中定义style皮肤颜色样式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<style name="AppTheme.Light.Blue" parent="Base.AppTheme">
<item name="colorPrimary">@color/material_light_blue</item>
<item name="colorPrimaryDark">@color/material_light_blue</item>
<item name="colorAccent">@color/material_light_blue</item>
</style>

<style name="AppTheme.Pink" parent="Base.AppTheme">
<item name="colorPrimary">@color/material_pink</item>
<item name="colorPrimaryDark">@color/material_pink</item>
<item name="colorAccent">@color/material_pink</item>
</style>

<style name="AppTheme.Red" parent="Base.AppTheme">
<item name="colorPrimary">@color/material_red</item>
<item name="colorPrimaryDark">@color/material_red</item>
<item name="colorAccent">@color/material_red</item>
</style>

<style name="AppTheme.Purple" parent="Base.AppTheme">
<item name="colorPrimary">@color/material_purple</item>
<item name="colorPrimaryDark">@color/material_purple</item>
<item name="colorAccent">@color/material_purple</item>
</style>

这里就列举了4款皮肤style文件,由于Activity都是继承自AppCompatActivity,所以这里通过修改colorPrimary、colorPrimaryDark、colorAccent来达到换肤的目的。

二、在BaseActivity中通过setTheme()来应用皮肤对应的style

1
2
3
4
5
6
  @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.xxx);
// 只要在setContentView之前setTheme即可
}

三、如何让TextView或者ImageView跟随皮肤颜色设置?

对于TextView只需要在xml中动态引用下当前style的colorPrimary/colorPrimaryDark/colorAccent即可(这里引用的是colorPrimary):

1
2
3
4
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="?attr/colorPrimary"/>

ImageView和TextView一样:

1
2
3
4
5
<ImageView
android:layout_width="23dp"
android:layout_height="23dp"
android:src="@drawable/ic_rectangle"
android:tint="?attr/colorPrimary"/>