How to remove a preference from PreferenceActivity? - android

I'm using PreferenceActivity. How do I remove a preference? I cannot seem to get this to work:
Preference p = findPreference("grok");
boolean worked = getPreferenceScreen().removePreference(p);
// worked == false.
So the preference is found, but the removePreference() call fails. What's the right way to do this? I'm using a preference.xml file for the keys like so:
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="foo">
<CheckBoxPreference
android:key="grok" />
...
Thanks

you can remove only exact child in PreferenceGroup. So in your case, you should add some key to PreferenceCategory (with title="foo"), then findPreference with this key & then remove it child
XML:
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:key="category_foo"
android:title="foo">
<CheckBoxPreference
android:key="grok" />
...
Code:
Preference p = findPreference("grok");
// removing Preference
((PreferenceGroup) findPreference("category_foo")).removePreference(p);

Instead of setting multiple ids, you can get the entire tree of preferences and find the parent of any preference, and then remove any of its children preferences:
public static Map<Preference,PreferenceGroup> buildPreferenceParentTree(final PreferenceActivity activity)
{
final Map<Preference,PreferenceGroup> result=new HashMap<Preference,PreferenceGroup>();
final Stack<PreferenceGroup> curParents=new Stack<PreferenceGroup>();
curParents.add(activity.getPreferenceScreen());
while(!curParents.isEmpty())
{
final PreferenceGroup parent=curParents.pop();
final int childCount=parent.getPreferenceCount();
for(int i=0;i<childCount;++i)
{
final Preference child=parent.getPreference(i);
result.put(child,parent);
if(child instanceof PreferenceGroup)
curParents.push((PreferenceGroup)child);
}
}
return result;
}
example:
final Map<Preference,PreferenceGroup> preferenceParentTree=buildPreferenceParentTree(SettingsActivity.this);
final PreferenceGroup preferenceParent=preferenceParentTree.get(preferenceToRemove);
preferenceGroup.removePreference(preferenceToRemove);
EDIT: seems there is a new API for this :
https://developer.android.com/reference/androidx/preference/Preference#setVisible(boolean)
I'm not sure if currently it's available or not, though.

Related

Checkboxpreference change value

I have checkboxpreference in preference activity and I want that when one of the checkbox is enabled then other checkbox should get to disable and vice versa.
I wants to do that from my main class activity.
Here is my code:
Preferencecheckbox.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:defaultValue="true"
android:icon="#drawable/img"
android:key="check1"
android:title="first" />
<CheckBoxPreference
android:defaultValue="false"
android:icon="#drawable/img2"
android:key="check2"
android:title="second" />
</PreferenceScreen>
Preferenceclass.java
public class preferenceclass extends PreferenceActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferencecheckbox);
}
You need to add a dependency to the checkbox you need disabled.
Like this:
<CheckBoxPreference
android:defaultValue="false"
android:icon="#drawable/img2"
android:key="check2"
android:title="second"
android:dependency="check1" />
Update
To disable other preferences via code.
final CheckBoxPreference checkbox2 = (CheakBoxPreference) findPreference("pref_checkbox2_key");
CheckBoxPreference switch = (CheakBoxPreference) findPreference("pref_switch_key");
switch.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
if (switch.isChecked()) {
checkbox2.setEnabled(false);
} else {
checkbox2.setEnabled(true);
}
return true;
}
});
persistCheckBoxState(switch, checkbox2);
To persist the change when activity is closed, you need to get the preferences references like this and add directly below.
public void persistCheckBoxState (CheckBoxPreference switch, CheckBoxPreference checkbox2) {
if (switch.isChecked ()){
checkbox2.setEnabled(false);
} else {
checkbox2.setEnabled(true);
}
}
Maybe a ListPreference is more what you want. From a usability point of view this would make more sense. When you have to choose one selection out of many this would be the most obvious way to do it. See this post for further instructions

Setting Preferences Android

I´m having trouble with setting preferences in my app.
In the main layout I have the button to open the settings layout:
Button btnPreferences = (Button) findViewById(R.id.btnPreferences);
btnPreferences.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent("com.absolutkarlos.AppPreferenceActivity");
startActivity(i);
}
});
Then, it open the PreferenceActivity:
public class AppPreferenceActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//--load the preferences from an XML file---
addPreferencesFromResource(R.xml.user_references);
}
}
The xml file:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Category 1">
<CheckBoxPreference
android:title="Checkbox"
android:defaultValue="false"
android:summary="True of False"
android:key="checkboxPref" />
</PreferenceCategory>
<PreferenceCategory android:title="Category 2">
<EditTextPreference
android:summary="Enter a string"
android:defaultValue="#string/food"
android:title="Edit Text"
android:key="editTextPref"
android:name="#string/name"/>
<RingtonePreference
android:summary="Select a ringtone"
android:title="Ringtones"
android:key="ringtonePref"
android:name="Ringtone Preference" />
<PreferenceScreen
android:title="Second Preference Screen"
android:summary=
"Click here to go to the second Preference Screen"
android:key="secondPrefScreenPref" >
<EditTextPreference
android:summary="Enter a string"
android:title="Edit Text (second Screen)"
android:key="secondEditTextPref"
android:name="EditText" />
</PreferenceScreen>
</PreferenceCategory>
</PreferenceScreen>
Everything looks like its going to work ok, but when I test it, don´t save the string I want it to save.
I Mean, I click the setting button, open the setting layout, I write a text on the EditTextPreference call NAME, but it doesn´t save it, instead the LogCat: sendUserActionEvet() mView == null
So, what I´m doing wrong? Did I miss a step? or forgot to add something?
Basically, I just want to user write his name as part of the settings, this name will be shown at the main layout as a big title. The user can write a nickname if he want. It´s just a string that the app must remember always.
Thanks for your help...
As you might have read, the message:
LogCat: sendUserActionEvet() mView == null
can be ignored on S4 devices.
You need read the value of Preference, and change it, for his title, on your AppPreferenceActivity, set onResume method:
#Override
public void onResume(){
super.onResume();
EditTextPreference preference = (EditTextPreference) findPreference("secondEditTextPref");
preference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
preference.setTitle(newValue.toString());
return true;
}
});
String name = preference.getText();
if(name != null)
preference.setTitle(name);
}
Also, you must remove addPreferencesFromResource method, because is deprecated. You should use onBuildHeaders method. Here you can see an example of PreferenceActivity.

How to remove PreferenceCategory programmatically?

I need to remove a PreferenceCategory programmatically. I could remove the individual preferences with the following code but I need to remove (disable) whole PreferenceCategory as well.
PreferenceScreen preferenceScreen = getPreferenceScreen();
EditTextPreference etp = (EditTextPreference) preferenceScreen.findPreference("pref22");
((PreferenceGroup) findPreference("prefcat")).removePreference(etp);
Edit: Here's the working code for a PreferenceCategory "prefcat" and a child preference "pref22":
PreferenceScreen preferenceScreen = getPreferenceScreen();
EditTextPreference etp = (EditTextPreference) preferenceScreen.findPreference("pref22");
PreferenceGroup preferenceGroup = (PreferenceGroup) findPreference("prefcat");
if (preferenceGroup != null) {
preferenceGroup.removePreference(etp);
preferenceScreen.removePreference(preferenceGroup);
}
you can hide a category by getting reference to PreferenceScreen:
I your xml :
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:key="#string/preferenceScreen">
//set all you values
//Preference, PreferenceCategory and/or CheckBoxPreference
</PreferenceScreen>
in you string.xml :
don't forgot to set this new string
<string name="preferenceScreen" translatable="false">preferenceScreen</string>
in you code:
preferenceScreen = (PreferenceScreen) findPreference(getResources().getString(R.string.preferenceScreen));
and then remove the category from your PreferenceScreen :
myCategory = (PreferenceCategory) findPreference(getResources().getString(R.string.my_category));
myPreferenceScreen.removePreference(myCategory);
Don't load the PreferenceCategory in the first place.
If you are defining your preferences in Java, don't create the PreferenceCategory.
If you are defining your preferences in XML, use three XML files:
One for stuff before this magic category
One for the magic category
One for stuff after this magic category
In situations where you want the category, load all three XML files. In situations where you do not want the category, load only the first and third XML files.
Provide a key for your PreferenceScreen and your PreferenceCategory in XML:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:key="preferenceScreen" >
<PreferenceCategory
android:summary="#string/settings_billing_summary"
android:title="Title"
android:key="myPrefCat" >
<Preference
android:key="someKey"
android:summary="Sum"
android:title="Title" />
</PreferenceCategory>
</PreferenceScreen>
From your class, you can now refer to your preferenceScreen and preferenceCategory and use the removePreference() method to remove the preference from the screen:
PreferenceScreen preferenceScreen = (PreferenceScreen) findPreference("preferenceScreen");
PreferenceCategory myPrefCat = (PreferenceCategory) findPreference("myPrefCat");
preferenceScreen.removePreference(myPrefCat);
This answer is based on douarbou's answer which appears to be outdated, but is basically the same.
You can find the entire child-parent tree by traversing over all of the preferences and then check which is the parent of any preference you wish, even without using the id of the parent:
public static Map<Preference,PreferenceGroup> buildPreferenceParentTree(final PreferenceActivity activity)
{
final Map<Preference,PreferenceGroup> result=new HashMap<Preference,PreferenceGroup>();
final Stack<PreferenceGroup> curParents=new Stack<PreferenceGroup>();
curParents.add(activity.getPreferenceScreen());
while(!curParents.isEmpty())
{
final PreferenceGroup parent=curParents.pop();
final int childCount=parent.getPreferenceCount();
for(int i=0;i<childCount;++i)
{
final Preference child=parent.getPreference(i);
result.put(child,parent);
if(child instanceof PreferenceGroup)
curParents.push((PreferenceGroup)child);
}
}
return result;
}
sample usage:
final Map<Preference,PreferenceGroup> preferenceParentTree=buildPreferenceParentTree(SettingsActivity.this);
final PreferenceGroup preferenceGroup=preferenceParentTree.get(preferenceToRemove);
preferenceGroup.removePreference(preferenceToRemove);
EDIT: seems there is a new API for this :
https://developer.android.com/reference/androidx/preference/Preference#setVisible(boolean)
I'm not sure if currently it's available or not, though.

How to create RadioButton group in preference.xml window?

I'm beginner in Java Android developing. I'm using Eclipse SDK 3.6.1 version. I have a preferences window with two checkbox and one back button.
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="PIN requirement">
<CheckBoxPreference
android:title="Use PIN"
android:defaultValue="true"
android:key="checkboxPref" />
<CheckBoxPreference
android:title="Don't use PIN"
android:defaultValue="false"
android:key="checkboxPref2" />
</PreferenceCategory>
<PreferenceCategory>
<Preference
android:title="Back"
android:key="customPref" />
</PreferenceCategory>
</PreferenceScreen>
How to change two CheckBox in to the RadioButton group?
If you need just to enable or disable using PIN, only one CheckBoxPreference will be enough in this case (see example code below, First Category). RadioButtons are usually used, when you need to choose something from a list of settings (ListPreference) - for example (see example code, Second Category), to pick a color.
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="First Category">
<CheckBoxPreference
android:title="Using PIN"
android:defaultValue="false"
android:key="checkboxPref"
android:summaryOn="Disable PIN"
android:summaryOff="Enable PIN"/>
</PreferenceCategory>
<PreferenceCategory
android:title="Second Category">
<ListPreference
android:title="Pick your favourite color"
android:key="listPref"
android:defaultValue="4"
android:entries="#array/listArray"
android:entryValues="#array/listValues" />
</PreferenceCategory>
</PreferenceScreen>
The source code for this example will be:
public class PreferencesHelpExample extends PreferenceActivity implements OnSharedPreferenceChangeListener {
public static final String KEY_LIST_PREFERENCE = "listPref";
private ListPreference mListPreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
// Get a reference to the preferences
mListPreference = (ListPreference)getPreferenceScreen().findPreference(KEY_LIST_PREFERENCE);
}
#Override
protected void onResume() {
super.onResume();
// Setup the initial values
mListPreference.setSummary("Current value is " + mListPreference.getEntry().toString());
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// Set new summary, when a preference value changes
if (key.equals(KEY_LIST_PREFERENCE)) {
mListPreference.setSummary("Current value is " + mListPreference.getEntry().toString());
}
}
}
For ListPreference you will also need an arrays.xml file, which is located in the "values" folder:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="listArray">
<item>red</item>
<item>orange</item>
<item>yellow</item>
<item>green</item>
<item>blue</item>
<item>violet</item>
</string-array>
<string-array name="listValues">
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
<item>5</item>
<item>6</item>
</string-array>
</resources>
See also some great examples, working with PreferenceActivity - they helped me a lot:
Android Preferences;
How to create a group of RadioButtons instead of a list;
How to display the current value of an Android Preference in the Preference summary?
In some situations, having Preferences behave as radio buttons is a nice feature e.g a simple way of including summary text under each option.
Making a group of checkboxes behave like a group of radio buttons is fairly simple. To do this in Preferences, register all the checkboxes in the group to the same OnPreferenceChangeListener then in this listener use findPreference() to find the other checkboxes and call setChecked(false);
public boolean onPreferenceChange(Preference preference, Object newValue) {
String key = preference.getKey();
if (key.equals("checkboxPref")) {
//Reset other items
CheckBoxPreference p = (CheckBoxPreference)findPreference("checkboxPref2");
p.setChecked(false);
}
else if (key.equals("checkboxPref2")) {
//Reset other items
CheckBoxPreference p = (CheckBoxPreference)findPreference("checkboxPref");
p.setChecked(false);
}
//Force the current focused checkbox to always stay checked when pressed
//i.e confirms value when newValue is checked (true) and discards newValue
//when newValue is unchecked (false)
return (Boolean)newValue;
}
The only downside is that the checkboxes will not look like radio buttons...
I think this is pretty simple if that is what you want:
Add the checkboxes at the preferenses xml like that:
<CheckBoxPreference
android:key="prefkey_cbp_1"
android:summary="#string/prefkey_cbp_1"
android:title="#string/prefkey_cbp_1"
android:defaultValue="false" />
<CheckBoxPreference
android:key="prefkey_cbp_2"
android:summary="#string/prefkey_cbp_2"
android:title="#string/prefkey_cbp_2"
android:defaultValue="false" />
//etc...
At the preferences class onCreate build an CheckBoxPreference array or list or whatever you like, like that:
ArrayList<CheckBoxPreference> cbp_list = new ArrayList<CheckBoxPreference>();
cbp_list.add((CheckBoxPreference) getPreferenceManager()
.findPreference(PreferencesProtocol.prefkey_cbp_1));
cbp_list.add((CheckBoxPreference) getPreferenceManager()
.findPreference(PreferencesProtocol.prefkey_cbp_2));
Make your preferences class implement OnPreferenceClickListener and set the OnPreferenceClickListener to the checkboxes like that :
for (CheckBoxPreference cbp : cbp_list) {
cbp.setOnPreferenceClickListener(this);
}
Then just override the onPreferenceClick and handle any click. For example if you want checkboxes to perform like radio buttons (in the same radiogroup), meaning, only one checkbox at the time to be check, do something like that:
#Override
public boolean onPreferenceClick(Preference arg0) {
for (CheckBoxPreference cbp : cbp_list) {
if (!cbp.getKey().equals(arg0.getKey()) && cbp.isChecked()) {
cbp.setChecked(false);
}
}
return false;
}
try this:
#Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, #NonNull Preference preference) {
CheckBoxPreference cb1 = null;
CheckBoxPreference cb2 = null;
ListAdapter adapter = preferenceScreen.getRootAdapter();
for(int i = 0; i < preferenceScreen.getRootAdapter().getCount(); i++)
{
//attention to type and key
Preference pref = (Preference) adapter.getItem(i);
if (pref == null || pref.getKey() == null)
continue;
if (pref.getKey().equals(getString(R.string.tag_preference_key_always_zoom_to_akt_position)))
cb1 = (CheckBoxPreference) pref;
if (pref.getKey().equals(getString(R.string.tag_preference_key_always_zoom_to_last_location)))
cb2 = (CheckBoxPreference) pref;
if (cb1 != null && cb2 != null)
break;
}
//be safe
if (cb1 == null || cb2 == null)
return super.onPreferenceTreeClick(preferenceScreen, preference);
if (preference.getKey().equals(getString(R.string.tag_preference_key_always_zoom_to_akt_position))) {
CheckBoxPreference cb = (CheckBoxPreference) preference;
cb2.setChecked(!cb.isChecked());
}
if (preference.getKey().equals(getString(R.string.tag_preference_key_always_zoom_to_last_location))) {
CheckBoxPreference cb = (CheckBoxPreference) preference;
cb1.setChecked(!cb.isChecked());
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}

How to show and hide preferences on Android dynamically?

Is there a way to dynamically show and hide preferences? In my case, I have a checkbox preference that would disable or enable one of 2 preference groups ("with-" and "without-handicap" groups). While this would be the ideal GUI in a desktop environment, the "with-handicap" takes up nearly the whole screen, while the other, "without-handicap" takes up only a small portion of the screen.
Rather than showing both groups at the same time, I'd like to show only one of them at a time, and dynamically show or hide the 2 groups when the checkbox changes. Is there a way to do this?
From a PreferenceActivity call
Preference somePreference = findPreference(SOME_PREFERENCE_KEY);
PreferenceScreen preferenceScreen = getPreferenceScreen();
preferenceScreen.removePreference(somePreference);
you can later call:
preferenceScreen.addPreference(somePreference);
The only a little bit tricky part is getting the order correct when adding back in. Look at PreferenceScreen documentation, particularly it's base class, PreferenceGroup for details.
Note: The above will only work for immediate children of a PreferenceScreen. If there is a PreferenceCategory in between, you need to remove the preference from its parent PreferenceCategory, not the PreferenceScreen. First to ensure the PreferenceCategory has an android:key attribute set in the XML file. Then:
Preference somePreference = findPreference(SOME_PREFERENCE_KEY);
PreferenceCategory preferenceCategory = (PreferenceCategory) findPreference(SOME_PREFERENCE_CATEGORY_KEY);
preferenceCategory.removePreference(somePreference);
and:
preferenceCategory.addPreference(somePreference);
Not exactly hiding/showing but if you only want disabling/enabling preference depending on another preference you can specify android:dependency="preferenceKey" or Preference.setDependency(String)
Example from developer.android.com:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="pref_sync"
android:title="#string/pref_sync"
android:summary="#string/pref_sync_summ"
android:defaultValue="true" />
<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" />
</PreferenceScreen>
I recommend using V7 preference, it has setVisible() method. But I have not tried it yet.
If you want to implement the hiding of the preference completely in the Preference, here is one example. Does not allow to make it visible again, though.
public class RemovablePreference extends Preference {
#Override
protected void onBindView(View view) {
super.onBindView(view);
updateVisibility(); // possibly a better place available?
}
private void updateVisibility() {
Context context = getContext(); // should be a PreferenceActivity
if (context instanceof PreferenceActivity) {
updateVisibility((PreferenceActivity)context);
}
}
private void updateVisibility(PreferenceActivity activity) {
updateVisibility(getPreferenceScreen(activity));
}
private PreferenceScreen getPreferenceScreen(PreferenceActivity activity) {
if (activity.getPreferenceScreen() != null) {
return activity.getPreferenceScreen(); // for old implementations
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
Fragment fragment = activity.getFragmentManager().findFragmentById(android.R.id.content);
if (fragment instanceof PreferenceFragment) {
return ((PreferenceFragment) fragment).getPreferenceScreen();
}
}
return null;
}
private void updateVisibility(PreferenceScreen screen) {
if (!isVisible() && screen != null) {
hidePreference(screen, this);
}
}
private boolean hidePreference(PreferenceGroup prefGroup, Preference removedPreference) {
boolean removed = false;
if (prefGroup.removePreference(removedPreference)) {
removed = true;
}
for (int i = 0; i < prefGroup.getPreferenceCount(); i++) {
Preference preference = prefGroup.getPreference(i);
if (preference instanceof PreferenceGroup) {
PreferenceGroup prefGroup2 = (PreferenceGroup)preference;
if (hidePreference(prefGroup2, this)) {
// The whole group is now empty -> remove also the group
if (prefGroup2.getPreferenceCount() == 0) {
removed = true;
prefGroup.removePreference(prefGroup2);
}
}
}
}
return removed;
}
protected boolean isVisible() {
return true; // override
}
I needed something similar: toggling a switch to hide or show two extra preferences. Check out the sample app from Android-Support-Preference-V7-Fix which bring some new preference types and fixes some issues from the official library. There's an example there to toggle a checkbox to show or hide a preference category.
In the fragment that extends PreferenceFragmentCompatDividers, you could use something like:
findPreference("pref_show_extra_stuff").setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
findPreference("pref_extra_stuff_01").setVisible((Boolean) newValue);
findPreference("pref_extra_stuff_02").setVisible((Boolean) newValue);
return true;
}
});
pref_extra_stuff_01 and pref_extra_stuff_02 are the two preferences that are hidden when pref_show_extra_stuff is toggled.
For hiding preferences dynamically, I created an if-condition upon whose value I decide whether I want the pref to show or not. To do the actual hiding, I have been using:
findPreference(getString(R.string.pref_key)).setLayoutResource(R.layout.hidden);
The tricky part is to make it visible again. There is no direct way to do it except to recreate the layout. If the value of the if-condition is false, which means the pref should be visible, then the code to hide the pref will never be executed, thus resulting in a visible pref. Here is how to recreate the layout (in my case, I am extending a PreferencesListFragment):
getActivity().recreate();
I hope that was helpful.
Instead of doing this in onCreate in the settings activity:
getSupportFragmentManager().beginTransaction()
.replace(R.id.settings_container, new SettingsFragment()).commit();
You can initialize a global variable for the settings fragment and set it up like this:
settingsFragment = new SettingsFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.settings_container, settingsFragment).commit();
Then further down you can set up an OnSharedPreferenceChangeListener with a global SharedPreferences.OnSharedPreferenceChangeListener to set up what should be shown or hidden when you change preferences:
// Global SharedPreferences.OnSharedPreferenceChangeListener
sharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener()
{
Override
public void onSharedPreferenceChanged(SharedPreferences preferences, String key)
{
if (key.equals("switch key"))
{
boolean newPref = preferences.getBoolean("switch key", true);
settingsFragment.findPreference("seekbar key").setVisible(newPref);
}
}
};
sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener);
Then in onCreate in the settings fragment you can do something like this to set what should be hidden based on existing preferences:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
if (!sharedPreferences.getBoolean("switch key", true)
{
SeekBarPreference seekBarPreference = findPreference("seekbar key");
seekBarPreference.setVisible(false);
}

Categories

Resources