Activate and deactivate a preference - android

I need an example-tutorial how to activate and deactivate an element in preference activity.
For example in the picture below when the Wi-Fi check box is unselected I can not touch the Network notification check box and it turns gray, when the Wi-Fi check box is selected then I can touch the other check box.
Also how can I populate the Add Wi-Fi network tab when the whi-fi checkbox is enabled?

We need to add in out preferences.xml file
in the preference which is depending from another preference the android:dependency="" code.
For example :
<CheckBoxPreference
android:key="checkBox"
android:summary="On/Off"
android:title="Enable" />
<ListPreference
android:entries="#array/listOptions"
android:entryValues="#array/listValues"
android:key="listpref"
android:summary="List preference example"
android:title="List preference"
android:dependency="checkBox" />

Your preferences activity should implement OnSharedPreferenceChangeListener. Be sure to register and unregister the activity with the listener.
Then in both onResume() and onSharedPreferenceChanged methods evaluate the state of the controlling preference to determine if the dependant preference should be enabled or disabled.
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
final String key) {
if (key.equals(PREFERENCE_KEY)) {
// handle setting enabled or disabled depending on value of preference
if (sharedPreferences.getBoolean(key, false)) {
// prefField.setenabled(true);
} else {
// prefField.setenabled(false);
}
}
}
If you also use a PreferenceCategory then you may also look to enable or disable the category as a whole.

When preference activity starts in onResume method check wifi connection status, or whatever you want and enable/disable appropriate preference.
It may looks similar to this, simple example, just to give you a general idea.
#Override
protected void onResume() {
super.onResume();
boolean isConnected = getConnectionStatus();
if(isConnected) {
connPreference.setEnabled(false);
} else {
connPreference.setEnabled(true);
}
}

Related

how to turn on SwitchPreference programatically on Android

I've a settings fragment which load a xml with a default settings page, I also added one click listener to one specific preference
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.settings);
preferences.findPreference(getString(R.string.pref_custom_list)).setOnPreferenceChangeListener(this);
//other stuff.....
this works fine, when user clicks triggers an event and i can check some info about the switch including deny the change...
But i would like to turn on/off other switches in the same screen when this even happen
i tried to
preferences.findPreference(getString(R.string.xpto)).setEnabled(true);
but it doesn't turn any switch on or off... it just set the view enabled or disabled for clicks
if i do something like
PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("xpto",true).apply();
It does change the preference, but the changes are not loaded to the screen so user doesn't know
how can i switch some preference on or off programatically and make it reflect to the preference screen
You can use SwitchPreferenceCompat.
<SwitchPreferenceCompat
app:key="key"
app:title="Some Confs" />
Try this in your fragment if you are using SwitchPreferenceCompat as above.
SwitchPreferenceCompat switchPref = findPreference("key");
switchPref.setChecked(true);
You're looking for setChecked(), not setEnabled():
preferences.findPreference(getString(R.string.xpto)).setChecked(true);
I think you need to implement a listener when the SharedPreferences change.
SharedPreferences.OnSharedPreferenceChangeListener spChanged = new
SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// change the Switch Preference state here
}
};
Then when the prefs change, you can change the user's screen to match it.
For your reference:
How to detect if changes were made in the preferences?

Hide item in Android preferences menu

my Application has a Preferences menu. there are 2 checkbox: "Enable Music", and "Show Hints". What I want is, There is Music List will show if check "Enable Music", else Music list will not enable. My code is:
boolean OPT_MUSIC_DEF = true;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
if (!PreferenceManager.getDefaultSharedPreferences(this).getBoolean(OPT_MUSIC, OPT_MUSIC_DEF)){
Preference list = findPreference("music_list");
list.setEnabled(false);
}
}
There is no error, but it work incorrect. When I unCheck "Enable Music" Music List did not hide right away, I must back and go to menu again to see Music List is hide.
Any way to make it hidden directly after uncheck "Enable Music" item?
thank for help me!
There is built in functionality to do exactly what you're trying to do. In your preferences.xml file set the dependency for the music_list preference to depend on the music_enable preference.
For example:
<android.preference.CheckBoxPreference
android:key="music_enable"
android:defaultValue="false"
android:title="Enable Music"
/>
<android.preference.ListPreference
android:key="music_list"
...
android:dependency="music_enable"
/>
Whenever the user checks the "music_enable" check box the "music_list" will be enabled; when they uncheck the "music_enable" check box the "music_list" will be disabled.
Make sure to call onContentChanged() right after disabling the preference.
If you want to force refresh the appearance of your preference, just do:
Preference myPref = findPreference("mypref");
myPref.setDefaultValue((int)(Math.random()*1000); // you can also backup the value before and reset it after if you need to keep a default value
Not the perfect solution, but it will surely force Android to refresh your preferences.
BTW, I tried Paul-Jan solution but unluckily it didn't work, it seems that onContentChanged() will just do nothing if no value is changed.

Any examples for "onDialogClosed"?

Can anyone give me an example or explain me how i subscribe to the
onDialogClosed method of an EditTextPreference?
http://developer.android.com/reference/android/preference/EditTextPreference.html#onDialogClosed%28boolean%29
I want to know when a dialog had its OK button clicked
and then retrive the information from the EditTextPreference.
Is there any examples/tutorials of this available or can anyone point
me in the right direction?
Thank you.
Just for completion: Since EditTextPreference is a Preference, you can use a OnPreferenceChangeListener. That will be called when the preference is changed. Check for the EditTextPreferences key in the callback and retrieve the new value to act on it. This is especially useful when the preference can be changed in more than one place or will be changed in the background by your app (e.g. writing defaults back when clicking a "default settings" button), since every change will trigger that callback (when your register it global on your SharedPreferences). The onDialogClosed will only be triggered when the user closed the actual dialog.
If you want to watch the single preference you can also use the EditTextPreference.setOnPreferenceChangedListener() function to assign a listener to that preference only.
OnPreferenceChangeListener documentation
You can make something like that :
#Override
protected void onDialogClosed(boolean positiveResult) {
if (positiveResult) {
String text=MyEditText.getText();
}
else {
// cancel hit
}
}

How to Initialize Preferences Screen on First Invocation?

I believe I am correctly initializing preferences from XML. My Preferences Screen also works properly and reflects the correct user selected settings.
However, upon first invocation of that Preferences Screen, none of the settings are checked (checkbox) or selected (list). This, of course, confuses the user as it doesn't reflect the current (default/initial) value.
Since all I do to invoke the Preferences Screen is
startActivity(new Intent(this, EditPreferences.class));
And my EditPreferences class only contains:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.usersettings);
}
I am not sure where or how to tell it to pre-initialize the visual display with the default setting.
I have this hunch that all I am missing is a single line somewhere, but I don't know where: XML file? override a method in EditPreferences? Other?
Can't you define the default value in the XML itself?
<CheckBoxPreference ...
android:defaultValue="true"
... />
You can specify a default value on a preference (in your xml layout for example):
<EditTextPreference android:defaultValue="whatever" />

ListPreference with a max number of selectable options

I want to have an element in my preference menu that does the following:
Show a list of options.
Many are selectable
Maximum amount of options to be chosen 2.
Possibilities I thought of:
Doing a separated PreferenceScreen and showing options as checkBoxes, but I don't know where to place the logic of max 2 options.
Extending DialogPreference and doing it by hand.
What's the best way?
Extending DialogPreference would get you the closest in terms of look-and-feel; the Preference classes are fairly unflexible and un-extendable in my experience.
I can't remember too much about PreferenceScreen, but I imagine it's similar.
In an app I worked on, we ended up using separate activities, launched via Intent from a Preference item onClick. This allowed us to easily develop preference screens that require validation logic a bit more complex than the usual.
You can put the logic of maximum two options in a OnSharedPreferenceChangeListener.
So you just listen to all the preferences as they change and update them if an invalid combination is selected.
So your code would be something like the following:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,String key) {
//Code to calcuate how many are selected
int code = numberSelected();
if (count > 2) {
sharedPreferences.edit().putBoolean(key,false).commit();
Toast.makeText(this,"Can't select more than two!",Toast.LENGTH_LONG).show();
}
}
If you create your own PreferenceActivity that implements OnSharedPreferenceChangeListener you can enable the listener to be listening only when required doing something like this:
#Override
protected void onResume() {
super.onResume();
//Register the listener
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}

Categories

Resources