Android主题切换
-
1.案例演示:
2.步骤:
- 1.编写styles文件,例如以下:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
</style>
<style name="RedTheme" parent="AppTheme">
<!-- android:windowBackground用于控制窗体颜色. -->
<item name="android:windowBackground">@color/redColor</item>
<item name="text_color">@color/blackColor</item>
<item name="title_color">@color/titleColor</item>
</style>
<style name="BlueTheme" parent="AppTheme">
<item name="android:windowBackground">@color/blueColor</item>
<item name="text_color">@color/whiteColor</item>
<item name="title_color">@color/redColor</item>
</style>
</resources>
- 2.创建theme_attrs.xml,自定义其他属性style:
<resources>
<attr name="text_color" format="reference"/>
<attr name="title_color" format="reference"/>
</resources>
- 3.在layout布局里面使用占位符进行引用:
//背景颜色:
android:background="?android:attr/windowBackground"
//TextView颜色:
android:textColor="?attr/text_color"
- 4.在Activity中执行切换操作:
//重新调用onCreate()方法
recreate();
//要在setContentView之前调用
setTheme(currentStyle);
- 3.GitHub源码:点我