我正在开发一个壁纸应用程序,它可以使用带有深色操作栏的 Holo Light、Holo Light 或 Holo Dark 主题。我有一个偏好活动,应该允许所述应用程序的用户根据他/她的喜好在 3 之间进行切换。
以下是偏好活动的片段:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//add the prefernces.xml layout
addPreferencesFromResource(R.xml.prefs);
ActionBar bar = getActionBar();
bar.setTitle(R.string.settings);
bar.setDisplayHomeAsUpEnabled(true);
}
首选项.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<ListPreference android:entries="@array/theme"
android:entryValues="@array/themeValues"
android:title="Themes"
android:enabled="true"
android:key="theme"
android:summary="Select which holo theme you prefer."
/>
</PreferenceScreen>
主题.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="theme">
<item>Holo Light with Dark Action Bar</item>
<item>Holo Light</item>
<item>Holo Dark</item>
</string-array>
<string-array name="themeValues">
<item>@style/Theme_Light_DarkActionBar</item>
<item>@style/Theme_Light</item>
<item>@style/Theme_Dark</item>
</string-array>
</resources>
我在 WallpaperActivity.java 中使用的代码来设置主题:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String theme = prefs.getString("theme", "defaultTheme");
setAppTheme(theme);
setContentView(R.layout.activity_wallpaper);
void setAppTheme(String s) {
String[] theme = getResources().getStringArray(R.array.themeValues);
if (s.matches("theme_light-dark")) {
//Light-Dark
setTheme(R.style.Theme_Light_DarkActionBar);
}
else if (s.matches("theme_light")) {
//Light
setTheme(R.style.Theme_Light);
}
else if (s.matches("theme_dark")) {
//Dark
setTheme(R.style.Theme_Dark);
}
else {
//Oops
}
}
最后是一个 logcat 片段:
[ 01-10 05:36:17.947 2621:0xa3d E/AndroidRuntime ]
FATAL EXCEPTION: main
java.lang.NullPointerException
at android.preference.ListPreference.onDialogClosed(ListPreference.java:264)
at android.preference.DialogPreference.onDismiss(DialogPreference.java:381)
at android.app.Dialog$ListenersHandler.handleMessage(Dialog.java:1228)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
如果您还需要什么,请告诉我。谢谢!
更新:
似乎我收到一条警告,内容如下:
The value of the local variable theme is not used
对于线路:
String[] theme = getResources().getStringArray(R.array.themeValues);