I have a preference activity in which I have a PreferenceCheckBox.
My preference activity:
package com.tjs.balr;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class SettingsActivity extends PreferenceActivity{
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource( R.xml.preferences);
}
}
My checkbox:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Audio">
<CheckBoxPreference
android:id="@+id/checkSound"
android:summary="Turn sounds on or off"
android:defaultValue="true"
android:title="Sounds"
android:key="soundPref"
/>
</PreferenceCategory>
</PreferenceScreen>
In my main activity I try to get the value of my checkbox using:
private void showUserSettings() {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
musicPlaying = sharedPrefs.getBoolean("checkSound", true);
if(musicPlaying){
Toast.makeText(this, "music is turned on", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "music is turned off ", Toast.LENGTH_SHORT).show();
}
}
A LOT of people here on stackoverflow describe musicPlaying = sharedPrefs.getBoolean("checkSound", true);
as the way to get the value of the checkbox, but in my case it stays true. Mainly because I say the default value of checkSound
is true. Am I forgetting something in order to change the value of my PreferenceCheckBox? To my understanding of an PreferenceActivity all data is saved automatically, is this correct?
In getBoolean(key, defaultValue)
, you need to pass the Key not the id.
You get always true
because he dont find the CheckBox
with checkSound as key so it return the default value ( true
in your case).
To fix that, just change
musicPlaying = sharedPrefs.getBoolean("checkSound", true);
to
musicPlaying = sharedPrefs.getBoolean("soundPref", true);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.