我正在开发一个壁纸应用程序,可以使用Holo Light w / Dark Action Bar,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);
}
的prefs.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>
的themes.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);