Android的Theme主题切换

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/llayjun/article/details/82626113

简单的Theme换肤功能

效果截图

1、定义属性
先定义几个需要改变的属性,例如:

<!--换肤-->
    <attr name="userNameColor" format="color" />
    <attr name="commonColor" format="color" />
    <attr name="bgColor" format="color" />
    <attr name="itemColor" format="color" />
    <attr name="settingImage" format="reference" />
    <attr name="themeImage" format="reference" />

2、定义主题,在style中

    <style name="NightTheme" parent="AppTheme">
        <item name="userNameColor">@color/color_ffffff</item>
        <item name="commonColor">@color/color_68737f</item>
        <item name="bgColor">@color/color_1c232c</item>
        <item name="itemColor">@color/color_181f29</item>
        <item name="settingImage">@mipmap/settings_night</item>
        <item name="themeImage">@mipmap/theme_night</item>
    </style>

    <style name="DayTheme" parent="AppTheme">
        <item name="userNameColor">@color/color_000000</item>
        <item name="commonColor">@color/color_424242</item>
        <item name="bgColor">@color/color_ffffff</item>
        <item name="itemColor">@color/color_ffffff</item>
        <item name="settingImage">@mipmap/settings_day</item>
        <item name="themeImage">@mipmap/theme_day</item>
    </style>

3、在布局中使用

<LinearLayout
  android:id="@+id/ll_parent"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="?attr/bgColor">

<ListView
  android:id="@+id/lv_choose_project_item"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:divider="@null" />

</LinearLayout>

4、在onCreate中调用,需要再setContentView之前调用,这边配合sp,记录用户喜欢的主题

boolean theme = (boolean) SPUtil.getInstance(Const.ConstantSp.SP_THEME_FILE_NAME).get(Const.ConstantSp.SP_THEME_KEY, true);
if (theme ) {
  MainActivity.this.setTheme(R.style.DayTheme);
} else {
  MainActivity.this.setTheme(R.style.NightTheme);
}
setContentView(R.layout.activity_main);

5、在切换的地方启动

finish();
Intent intent = getIntent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
overridePendingTransition(0, 0);

总结

通过Theme切换主题:
优点:实现简单,配置简单
缺点:需要重启应用;是固定皮肤,不能动态切换

猜你喜欢

转载自blog.csdn.net/llayjun/article/details/82626113