1自定义部分属性
1. <?xml version="1.0" encoding="utf-8"?>
2. <resources>
3. <attr name="colorValue" format="color" />
4. <attr name="floatValue" format="float" />
5. <attr name="integerValue" format="integer" />
6. <attr name="booleanValue" format="boolean" />
7. <attr name="dimensionValue" format="dimension" />
8. <attr name="stringValue" format="string" />
9. <attr name="referenceValue" format="reference" />
10. </resources>
2定义主题
1. <style name="SwitchTheme1" parent="@android:style/Theme.Black">
2. <item name="colorValue">#FF00FF00</item>
3. <item name="floatValue">0.35</item>
4. <item name="integerValue">33</item>
5. <item name="booleanValue">true</item>
6. <item name="dimensionValue">76dp</item>
8. <item name="stringValue">@string/hello_world</item>
9. <item name="referenceValue">@drawable/hand</item>
10. </style>
11. <style name="SwitchTheme2" parent="@android:style/Theme.Wallpaper">
12. <item name="colorValue">#FFFFFF00</item>
13. <item name="floatValue">1.44</item>
14. <item name="integerValue">55</item>
15. <item name="booleanValue">false</item>
16. <item name="dimensionValue">76px</item>
17. <item name="stringValue">@string/action_settings</item>
18. <item name="referenceValue">@drawable/ic_launcher</item>
19. </style>
3在布局文件中使用
使用占位符“?”,在代码中切换属性
1. <TextView
2. android:id="@+id/themeText"
3. android:layout_width="wrap_content"
4. android:layout_height="wrap_content"
5. android:layout_alignParentTop="true"
6. android:layout_centerHorizontal="true"
7. android:text="?attr/stringValue" />
8.
9. <ImageView
10. android:id="@+id/theme_image"
11. android:layout_width="wrap_content"
12. android:layout_height="wrap_content"
13. android:layout_alignLeft="@+id/themeColor"
14. android:layout_below="@+id/themeColor"
15. android:src="?attr/referenceValue" />
4设置主题及布局文件
调用setTheme(@StyleRes final int resid)方法;
值得注意的是:“setTheme一定要在setContentView之前被调用”。要不然,界面都解析完了,再设置主题也不会触发重新创建界面。
1. @Override
2. protected void onCreate(Bundle savedInstanceState) {
3. super.onCreate(savedInstanceState);
4. if (useThemeBlack)
5. setTheme(R.style.SwitchTheme1);
6. else
7. setTheme(R.style.SwitchTheme2);
8. useThemeBlack = !useThemeBlack;
9. setContentView(R.layout.activity_theme_switch);
10. recreate();
11. // refreshUI();
11. }
12.
切换主题可以调用recreate(),此时activity会重启,屏幕会闪烁一下;
也可以自己根据主题来设置各个组件的属性,代码量比较大,效果比较平滑,用户体验较好!