Simple Theme skin changing function
Effect screenshots
1. Defining properties
First define several attributes that need to be changed, for example:
<!--Skin peeler-->
<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. Define a theme in 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. Use in layout
<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, calling in onCreate, you need to call before setContentView, this side with sp, record user favorite theme.
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. Start at the place of switching
finish();
Intent intent = getIntent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
overridePendingTransition(0, 0);
summary
Switch themes with Theme:
Advantages: simple implementation and configuration
Disadvantages: it needs to restart the application; it is fixed skin and cannot switch dynamically