SwitchPreference not triggering when pressed - android

I have the following which creates my settings page with two notification settings:
SettingsActivity.java
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class NotificationPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notification2);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
pref_notification2.xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<SwitchPreference
android:defaultValue="true"
android:key="notifications_team_pick"
android:title="Team Pick Reminders" />
<SwitchPreference
android:defaultValue="true"
android:key="notifications_results"
android:title="Results Notifications" />
</PreferenceScreen>
I was expecting that the following would be invoked when a notification option is pressed:
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
Log.d("Am I: ", "Here");
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
Log.d("Am I: ", "Here 2");
}
return true;
}
};
However, whatever I attempt I can not get anything to happen once the toggle is pressed. Any help would be appreciated, many thanks, Alan.
ADDED To Match a Suggestion:
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class NotificationPreferenceFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("I am at: ", "OnCreate extends");
addPreferencesFromResource(R.xml.pref_notification2);
}
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
//Your preference change method code.
Log.d("I am at: ", "OnCreate extends Hope");
return true;
}
}

you need to change your fragment like this -
package com.accelerate.myprefapplication;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.util.Log;
public class MyPreferencesActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
}
public static class MyPreferenceFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener {
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.path);
bindPreferenceSummaryToValue(findPreference("notifications_team_pick"));
bindPreferenceSummaryToValue(findPreference("notifications_results"));
}
private void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(this);
// Trigger the listener immediately with the preference's
// current value.
onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getBoolean(preference.getKey(), true));
}
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean state = Boolean.valueOf(newValue.toString());
Log.d("Am I: ", "Here");
return true;
}
}
}
I think this should for you.
Look for this answer.

That won't work. You will have to retrieve the value stored after interaction with switch. Use this to retrieve data.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String effchoice = prefs.getString("notifications_team_pick", getString(R.string.default_eff));
BTW, Your pref_notification2.xml is wrong. You have not set values to be saved and other things. Like this:
<ListPreference
android:dependency="pref_sync"
android:key="pref_syncConnectionType"
android:title="#string/pref_syncConnectionType"
android:dialogTitle="#string/pref_syncConnectionType"
android:entries="#array/pref_syncConnectionTypes_entries"
android:entryValues="#array/pref_syncConnectionTypes_values"
android:defaultValue="#string/pref_syncConnectionTypes_default" />
Read here

Related

Android SharedPreferences confusion

I am a beginner in android and I have a confusion regarding Shared Preferences implementation. My goal is to use a string where a user defines some text which will be used in MainFragment. Given the fact that user may change that string when application is running I need a listener as well. So according to one book so far I have a SettingsActivity and a SettingsFragment.
SettingsActivity so far:
public class SettingsActivity extends AppCompatActivity {
private SharedPreferences prefs;
private String stringIWantToSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
getFragmentManager().beginTransaction().
replace(android.R.id.content, new SettingsFragment(), "settings_fragment").commit();
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
}
#Override
protected void onResume() {
super.onResume();
stringIWantToSave = prefs.getString("stringIWantToSave", "myString");
}
}
SettingsFragment so far:
public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
private SharedPreferences sharedPreferences;
private String stringIWantToSave;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
}
#Override
public void onPause() {
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
super.onPause();
}
#Override
public void onResume() {
super.onResume();
sharedPreferences.getString("stringIWantToSave", "myString");
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
}
My questions are:
• In which method and how should I save the changed value from the user?
• How can I implement the listener so that it will inform the MainFragment that the string has changed?
1. To achieve the SettingsActivity with EditTextPreference, first you have to create a PreferenceScreen that contains EditTextPreference.
preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<EditTextPreference
android:key="pref_key_name"
android:title="Name"
android:summary="Enter your name here!"
android:dialogTitle="Enter name:">
</EditTextPreference>
</PreferenceScreen>
2. Create a Fragment extending PreferenceFragment. Do preference initialization and add OnSharedPreferenceChangeListener to update the UI when user input their name.
SettingsFragment.java:
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
// Preference Keys
public static final String KEY_PREF_NAME = "pref_key_name";
// Shared preference
SharedPreferences mSharedPreferences;
// Name preference
EditTextPreference mPreferenceName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
// Shared preference
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
// Name preference
mPreferenceName = (EditTextPreference) getPreferenceScreen().findPreference(KEY_PREF_NAME);
// Initialize
initPreferences();
}
public void initPreferences()
{
// Name
String oldName = mSharedPreferences.getString(KEY_PREF_NAME, "Enter your name here!");
// Update view
mPreferenceName.setSummary(oldName);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPref, String key) {
if(key.equals(KEY_PREF_NAME))
{
// Name
String currentName = sharedPref.getString(key, "DEFAULT_VALUE");
// Update view
mPreferenceName.setSummary(currentName);
}
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
}
3. Finally, Create SettingsActivity and show SettingsFragment on its FrameLayout.
SettingsActivity.java:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
// Settings Fragment
SettingsFragment settingsFragment = new SettingsFragment();
getFragmentManager().beginTransaction().replace(R.id.content, settingsFragment).commit();
}
#Override
protected void onResume() {
super.onResume();
}
}
HOW TO USE:
To use updated name from preference, get the name value from preference inside your activity or fragments onResume() method:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// Name
String name = sharedPreferences.getString(SettingsFragment.KEY_PREF_NAME, "DEFAULT_VALUE");
// Do something with name
................
........................
}
}
OUTPUT:
Hope this will help~

Change second Listpreference values in preference fragment when first Listpreference value selected

I have two Listprefence in a preference fragment and I want to refresh second Listpreference values when in first is selected something.
The Listpreferences are filled over the internet.
public class array extends PreferenceFragment {
public static String apref;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
final ListPreference array1Preference = (ListPreference)findPreference("array1");
setArray1PreferenceData(array1Preference);
array1Preference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
setArray1PreferenceData(array1Preference);
return true;}});
final ListPreference array2Preference = (ListPreference)FindPreference("array2");
setArray2PreferenceData(array2Preference);
array2Preference.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
setArray2PreferenceData(array2Preference);
return true;}});
}
public void setArray1PreferenceData(ListPreference array1Preference) {
new LoadArray1().execute();
}
public void setArray2PreferenceData(ListPreference array2Preference) {
String CPref = "array1";
SharedPreferences prefs = this.getActivity().getSharedPreferences(
"com.asdd.ck_preferences", Activity.MODE_PRIVATE);
apref = prefs.getString(CPref, "");
if (apref != "0") {
new LoadArray2().execute();
} else {
new LoadArray1().execute();
}
}
public class LoadArray1 extends AsyncTask<String, String, String> {
}
public class LoadArray2 extends AsyncTask<String, String, String> {
}
}
Finally I have got the answer my self.
array1Preference
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
apref = (String) newValue;//Sets the new value for second list loader (LoadArray2)
PreferenceManager.getDefaultSharedPreferences(getActivity()).edit().putString(key, "0").commit();//Clear in the preference file the 2nd listpreference selection data.
setArray2PreferenceData(array2Preference);//Reload data from server
array2Preference.setValue("0");//When in 1st selected something clear in 2nd the selection.
return true;
}
});

My ListPreference does not persist values when changing screen orientation

I have been stuck on this for days and tried different workarounds.
When I change screen orientation, the preference summary loses its value.
I have a custom ListPreference which when user clicks, pops up two choices for buddy - myself, and some other (in the actual program, user selects a buddy from Contacts).
I set the summary to the selected buddy's email address.
clicking preference pops up list preference which, depending on what is clicked, shows myself, or contacts picker to select a buddy.
'myself' was selected
flipping phone loses buddy
Here is a working program stripped to show the essentials.
class BuddyPreference2
public class BuddyPreference2 extends ListPreference {
String buddy;
private static final String TAG = "REGU";
public BuddyPreference2(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onDialogClosed(boolean positiveResult) {
if (positiveResult) {
persistString((String) buddy);
}
super.onDialogClosed(positiveResult);
}
#Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
super.onSetInitialValue(restoreValue, defaultValue);
if (restoreValue) {
// Restore existing state
buddy = this.getPersistedString("none set");
} else {
// Set default state from the XML attribute
buddy = (String) defaultValue;
persistString(buddy);
}
}
/*
* (non-Javadoc)
*
* #see android.preference.ListPreference#setValue(java.lang.String)
*/
#Override
public void setValue(String value) {
String s = new String(value);
super.setValue(s);
}
#Override
protected View onCreateDialogView() {
View view = super.onCreateDialogView();
return view;
}
}
user_prefs.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:key="#+id/pref_screen" >
<com.mypreferences.BuddyPreference2
android:entries="#array/buddy_entry"
android:entryValues="#array/buddy_value"
android:key="buddy_entry"
android:summary="my buddy"
android:title="my buddy" />
</PreferenceScreen>
class EditAlertPreferencesActivity
public class EditAlertPreferencesActivity extends Activity {
static final String BUDDY = "buddy_entry";
static final String TAG = "REGU";
private static final int CONTACT_PICKER_RESULT = 1001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_prefs_fragment);
}
// Fragment that displays the mesg preference
public static class UserPreferenceFragment extends PreferenceFragment {
protected static final String TAG = "REGU";
private OnSharedPreferenceChangeListener mListener;
private Preference buddyPreference;
String myEmailAddress;
String getMyEmailAddress() {
return "Myself" + " <me#my.com>";
}
public void setBuddySummary(String s) {
buddyPreference.setSummary(s);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myEmailAddress = getMyEmailAddress();
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.user_prefs);
buddyPreference = (Preference) getPreferenceManager().findPreference(BUDDY);
buddyPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String buddyChoice = (String) newValue;
if (buddyChoice.equals(getString(R.string.select))) {
Toast.makeText(getActivity(), "pick a contact", Toast.LENGTH_SHORT);
pickContact();
} else {
buddyPreference.setSummary(myEmailAddress);
}
return false;
}
});
// Attach a listener to update summary when msg changes
mListener = new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals(BUDDY)) {
buddyPreference.setSummary(sharedPreferences.getString(BUDDY, "none set"));
} else {
Log.e(TAG, "error; I do not recognize key " + key);
}
}
};
// Get SharedPreferences object managed by the PreferenceManager for
// this Fragment
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
// Register a listener on the SharedPreferences object
prefs.registerOnSharedPreferenceChangeListener(mListener);
// Invoke callback manually to display the msg
mListener.onSharedPreferenceChanged(prefs, BUDDY);
}
/*
* (non-Javadoc)
*
* #see android.preference.PreferenceFragment#onCreateView(android.view.
* LayoutInflater, android.view.ViewGroup, android.os.Bundle)
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
public void pickContact() {
String buddyEmailAddress = "Some Buddy " + " <buddy#email.com>";
setBuddySummary(buddyEmailAddress);
}
}
}
user_prefs_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.mypreferences.EditAlertPreferencesActivity$UserPreferenceFragment"
android:orientation="vertical"
android:id="#+id/userPreferenceFragment">
</fragment>
arrays.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="buddy_entry">
<item>myself</item>
<item>select a contact</item>
</string-array>
<string-array name="buddy_value">
<item>myself</item>
<item>select</item>
</string-array>
</resources>
class PreferencesActivityExample
public class PreferencesActivityExample extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Open a User Preferences Entry Activity
final Button button = (Button) findViewById(R.id.check_pref_button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(
PreferencesActivityExample.this,
EditAlertPreferencesActivity.class));
}
});
}
}
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="select">select</string>
</resources>
Issue is that the Preference value selected on the dialog is not saved/updated.
You can easily verify this Close the Activity and launch gain. You will still see the default value , noting to do with orientation change.
FIX: You need to return true to update the new value in preference.
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// do all your other stuff here
return true;
}
True to update the state of the Preference with the new value.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ListPreference listPreferenceCategory = (ListPreference) findPreference("pref_list_category");
listPreferenceCategory.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String category = (String) newValue;
CharSequence[] listEntries = listPreferenceCategory.getEntries();
int indexValue = listPreferenceCategory.findIndexOfValue(category);
listPreferenceCategory.setSummary(listEntries[indexValue]);
return true;
}
});
}
In xml:
<ListPreference
android:dialogTitle="#string/pref_category"
android:entries="#array/categories"
android:summary="#string/pref_category"
android:entryValues="#array/categories_value"
android:key="pref_list_category"
android:title="#string/pref_category"/>
That is my worked code. Try it !

OnPreferenceChangeListener dont gets called

I want to change the value of an EditTextPreference when an item in another ListPreference is clicked. But the OnPreferenceChangeListener never gets called.
Heres my code:
public class FragmentPreferences extends PreferenceActivity {
/*#Override
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.preference_headers, target);
}*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new UserPreferenceFragment())
.commit();
addPreferencesFromResource(R.xml.userpreferences);
ListPreference listPreference = (ListPreference) findPreference("PREF_MEASURE_UNITS");
if(listPreference.getValue()==null) {
// to ensure we don't get a null value
// set first value by default
listPreference.setValueIndex(0);
}
//listPreference.setSummary(listPreference.getValue().toString());
listPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
//preference.setSummary(newValue.toString());
EditTextPreference EditTextPreference = (EditTextPreference) findPreference("PREF_CAMERA_HEIGHT");
if (newValue.equals(0))
{
EditTextPreference.setText(String.format("%.1f",Float.valueOf(EditTextPreference.getText().replace(',','.'))*2.54f));
}
else if (newValue.equals(1))
EditTextPreference.setText(String.format("%.1f",Float.valueOf(EditTextPreference.getText().replace(',','.'))/2.54f));
return true;
}
});
}
Ive found the solution.
I had to place the code beneath
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new UserPreferenceFragment())
.commit();
in the class
public class UserPreferenceFragment extends PreferenceFragment{
Now its working

PreferenceActivity Settings not Saved

EDIT: I tried this new code but it still seems they are reset. Can anyone tell me, and propose a solution to my settings being reset?
public class UserSettingActivity extends PreferenceActivity implements OnPreferenceChangeListener{
static SwitchPreference mucus_stamps;
static SwitchPreference fertile_infertil;
static SwitchPreference cervical_mucus;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
/**
* Populate the activity with the top-level headers.
*/
#Override
public void onBuildHeaders(List<Header> target) {
Log.i("PROJECTCARUSO","onBuildHeaders");
loadHeadersFromResource(R.xml.preference_headers, target);
}
/**
* This fragment shows the preferences for the first header.
*/
public static class Prefs1Fragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.notification_settings);
}
}
/**
* This fragment shows the preferences for the second header.
*/
public static class Prefs2Fragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.charting_settings);
//findPreference("cervical_mucus").setOnPreferenceChangeListener(
mucus_stamps = (SwitchPreference) findPreference("mucus_stamps");
fertile_infertil = (SwitchPreference) findPreference("fertile_infertil");
cervical_mucus = (SwitchPreference) findPreference("cervical_mucus");
cervical_mucus.setOnPreferenceChangeListener(
new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// string test w/o "==" usage.
if (newValue.equals(false)) {
Log.i("PROJECTCARUSO","false");
mucus_stamps.setChecked(false);
fertile_infertil.setChecked(false);
} else {
Log.i("PROJECTCARUSO","true");
mucus_stamps.setChecked(true);
fertile_infertil.setChecked(true);
}
// true instead of false so the new value gets kept
return true;
};
});
if(!cervical_mucus.isChecked()){
mucus_stamps.setSelectable(false);
mucus_stamps.setEnabled(false);
fertile_infertil.setSelectable(false);
fertile_infertil.setEnabled(false);
} else {
mucus_stamps.setSelectable(true);
mucus_stamps.setEnabled(true);
fertile_infertil.setSelectable(true);
fertile_infertil.setEnabled(true);
}
}
}
protected void onPause()
{
super.onPause();
}
protected void onResume()
{
super.onResume();
}
#Override
public boolean onPreferenceChange(Preference arg0, Object arg1) {
// TODO Auto-generated method stub
return true;
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory
android:title="#string/pref_chart_profile"
android:textSize="20px">
<SwitchPreference
android:title="#+string/pref_symptothermal"
android:summary="#+string/pref_symptothermal_summary"
android:key="symptothermal"
android:defaultValue="true"
android:layout="#layout/pref_layout"/>
<SwitchPreference
android:id="#+id/cervical_mucus"
android:title="#+string/pref_cervical_mucus"
android:summary="#+string/pref_cervical_mucus_summary"
android:key="cervical_mucus"
android:defaultValue="true"
android:layout="#layout/pref_layout" />
<SwitchPreference
android:id="#+id/mucus_stamps"
android:title="#+string/pref_mucus_stamps"
android:summary="#+string/pref_mucus_stamps_summary"
android:key="mucus_stamps"
android:defaultValue="true"
android:layout="#layout/pref_layout" />
<SwitchPreference
android:id="#+id/fertile_infertil"
android:title="#+string/pref_fertile_infertile"
android:summary="#+string/pref_fertile_infertile_summary"
android:key="fertile_infertil"
android:defaultValue="true"
android:layout="#layout/pref_layout" />
</PreferenceCategory>
</PreferenceScreen>
Depending on what you want.
The value is saved(tested), but "selectable" is not a preference value. Therefore you have to set it when the preferencescreen is launched.
Do this:
Before your oncreate:
SwitchPreference mucus_stamps;
Then above your findPreference("mucus_stamps")
mucu_stamps = (SwitchPreference) findPreference("mucus_stamps");
Now, outside the onclicklistener, you can set it.
if(!mucus_stamps.isChecked()){
mucus_stamps.setSelectable(false);
mucus_stamps.setEnabled(false);
}
(I added "setEnablet" to show you that you can disable it aswell, not just make it "non-selectable". Selectable only says that you can't click anything outside the "off/on" area to change it to on/off.)
Personally I prefer to do it like this:
mucus_stamps = (SwitchPreference) findPreference("mucus_stamps");
mucus_stamps.setOnPreferenceChangeListener(
new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
//SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
// string test w/o "==" usage.
if (newValue.equals(false)) {
mucus_stamps.setChecked(false);
mucus_stamps.setSelectable(false);
} else {
mucus_stamps.setChecked(true);
}
// true instead of false so the new value gets kept
return true;
};
});
if(!mucus_stamps.isChecked()){
mucus_stamps.setSelectable(false);
mucus_stamps.setEnabled(false);
}
And, you don't need to implement OnPreferenceChangeListener when you do it the way you or I do. Not that it really matters.
:)

Categories

Resources