在應用開發中會常常遇到要求實現夜間模式
或者主題切換
具體例子以下,我會先講解第一種方法。
android
我今天主要是詳述第一種的實現方式:app
1
2
3
4
5
6
|
<application
android:
allowBackup="true"
android:
icon="@drawable/ic_launcher"
android:
label="@string/app_name"
android:
theme="@style/AppTheme">
</application>
|
1
2
3
4
5
6
7
8
9
|
<style
name="AppTheme"/>
<style
name="AppTheme.Light">
<
item name="root_background">@color/white</item>
</style>
<style
name="AppTheme.Dark">
<
item name="root_background">@color/black</item>
</style>
|
1
2
3
|
<declare-styleable name="Theme">
<attr name="root_background" format="reference|color" />
</declare-styleable>
|
1
2
3
4
5
6
|
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="?attr/root_background">
</RelativeLayout>
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme();
super.onCreate(savedInstanceState);
}
private void setTheme() {
mCurrentThemeResourceID = getThemeResourceID();
setTheme(mCurrentThemeResourceID);
}
private int getThemeResourceID() {
mIsNightModule = PreferencesUtils.getBoolean(
this, getResources().getString(R.string.is_night_mode));
return mIsNightModule ? R.style.AppTheme_Dark : R.style.AppTheme_Light;
}
public static void restartActivity(final Activity activity) {
if (activity == null) return;
final int enter_anim = android.R.anim.fade_in;
final int exit_anim = android.R.anim.fade_out;
activity.overridePendingTransition(enter_anim, exit_anim);
activity.finish();
activity.overridePendingTransition(enter_anim, exit_anim);
activity.startActivity(activity.getIntent());
}
private final boolean isThemeChanged() {
return getThemeResourceID() != mCurrentThemeResourceID;
}
@Override
protected void onResume() {
super.onResume();
if (isThemeChanged()) {
restartActivity(
this);
}
}
|
可用此方式實現多種theme的切換ide
之後會發博文講解如何實現主題下載,主題切換等功能。this
若是想和我討論,請在下面評論便可。spa