准备两套 style,要求参数item标签完全相同,标签值可以更改。
<style name="SwitchTheme1" parent="@android:style/Theme.Black"> <item name="colorValue">#FF00FF00</item> <item name="floatValue">0.35</item> <item name="integerValue">33</item> <item name="booleanValue">true</item> <item name="dimensionValue">76dp</item> <!-- 如果string类型不是填的引用而是直接放一个字符串,在布局文件中使用正常,但代码里获取的就有问题 --> <item name="stringValue">@string/hello_world</item> <item name="referenceValue">@drawable/hand</item> </style> <style name="SwitchTheme2" parent="@android:style/Theme.Wallpaper"> <item name="colorValue">#FFFFFF00</item> <item name="floatValue">1.44</item> <item name="integerValue">55</item> <item name="booleanValue">false</item> <item name="dimensionValue">76px</item> <item name="stringValue">@string/action_settings</item> <item name="referenceValue">@drawable/ic_launcher</item> </style>
每个需要不同的主题样式引用,修改 attr.xml 或者创建新的 resource 文件,attr 自定义属性
<?xml version="1.0" encoding="utf-8"?> <resources> <attr name="colorValue" format="color" /> <attr name="floatValue" format="float" /> <attr name="integerValue" format="integer" /> <attr name="booleanValue" format="boolean" /> <attr name="dimensionValue" format="dimension" /> <attr name="stringValue" format="string" /> <attr name="referenceValue" format="reference" /> </resources>
引用时使用 ?attr/自定义属性名
<ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="?attr/referenceValue" />
因为 setTheme 方法只在当前 Activity有效,所以如果要整体更改,需要将 setTheme 方法 放在 BaseActivity 中
setTheme(R.style.MyAppTheme); setContentView(R.layout.main_activity);
切换主题
// 结束当前 finish(); // 重新打开 Intent intent = getIntent(); startActivity(intent); // 关闭界面切换动画 overridePendingTransition(0,0);
此时如果返回之前的界面,主题修改不会起效,建议
singTask 模式 启动 MainActivity
Android 用户切换APP主题
最新推荐文章于 2022-08-23 15:54:10 发布