Android主題切換
-
1.案例演示:
ChangeTheme.gif 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.創(chuàng)建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中執(zhí)行切換操作:
//重新調用onCreate()方法
recreate();
//要在setContentView之前調用
setTheme(currentStyle);
- 3.GitHub源碼:點我