我正在製作一個動態壁紙,我需要在設置場景中更改車輛的速度,並且當我按下返回按鈕時需要反射回牆紙服務。在我的偏好活動,我省在類似這樣的共享偏好列表偏好的變化: -SharedPreference更改不反映在我的壁紙服務
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
ListPreference listPreference = (ListPreference) findPreference("listPref");
currValue = listPreference.getValue();
Log.e("LiveWallpaperSettings", "currvalue " + currValue);
listPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference arg0, Object arg1) {
SharedPreferences customSharedPreference = getSharedPreferences("Speed", LiveWallpaperSettings.MODE_PRIVATE);
SharedPreferences.Editor editor = customSharedPreference.edit();
editor.putString("Speed",currValue);
editor.commit();
return true;
}
});
我的壁紙服務使用andengine livewallpaper分機上。如果我想在服務中反映我的列表首選項中的更改,我該怎麼做。這是我做的,但似乎並沒有工作。
我的prefs.xml
<PreferenceCategory
android:title="Settings">
<ListPreference
android:title="Speed"
android:summary="Change the Speed"
android:key="listPref"
android:defaultValue="15"
android:entries="@array/listArray"
android:entryValues="@array/listValues"
/>
</PreferenceCategory>
我array.xml
<resources>
<string-array name = "listArray">
<item>Slow</item>
<item>Medium</item>
<item>Fast</item>
</string-array>
<string-array name = "listValues">
<item>5</item>
<item>15</item>
<item>30</item>
</string-array>
在我的服務我實現SharedPreferences.OnSharedPreferenceChangeListener並實現以下方法
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,String key) {
sharedPreferences = getSharedPreferences("Speed", MODE_PRIVATE);
strSpeedValue = sharedPreferences.getString("Speed", "5");
fltSpeedValue = Integer.parseInt(strSpeedValue);
final AutoParallaxBackground autoParallaxBackground = new AutoParallaxBackground(0, 0, 0, 10);
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(fltSpeedValue, new Sprite(0,mCamera.getHeight() - this.mParallaxLayer.getHeight(),this.mParallaxLayer, getVertexBufferObjectManager())));
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(0f, new Sprite(CAMERA_WIDTH/2 - 30, CAMERA_HEIGHT/2,this.mAutoLayer, getVertexBufferObjectManager())));
mMainScene.setBackground(autoParallaxBackground);
}
@Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this);
}
但我在列表首選項中改變的價值在我的服務中並未發生變化。難道我做錯了什麼?
嘿感謝您的回答,但問題是,onResume()被稱爲第一當服務onPopulateScene()之前首先啓動,這將創建一個空指針的值fltSpeedValue。 –
我不確定我是否理解。你是說如果你的onResume從喜好中提取速度,你不能在場景中設置它,因爲場景尚未創建?如果是這樣,爲什麼不只是從onPopulateScene函數中的首選項中提取值呢?如果場景已經被創建,你也可以從onResume中完成,但如果沒有,則忽略它。 –