I have a preference activity and have noticed that a list preference does not set default values when changed.
The Preference has these basic dynamics
If Checkbox = unticked --> list preference entry values = x
if Checkbox = ticked --> list preference entry values = z
When the app first runs default value is set but when I tick the checkbox no values apply after that.
CODE:
public class QuickPrefsActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
View title =(View)getWindow().findViewById(android.R.id.title);
FrameLayout titlebar=(FrameLayout)title.getParent();
TextView txt = (TextView)titlebar.getChildAt(0);
txt.setGravity(Gravity.CENTER);
CheckBoxPreference chckbox = (CheckBoxPreference)
findPreference("french");
if (chckbox.isChecked()) {
ListPreference newsPref = (ListPreference)
findPreference("news_feed");
newsPref.setEntryValues(getResources().
getStringArray(R.array.newsfeedfr));
newsPref.setDefaultValue(1);
} else {
ListPreference news2Pref = (ListPreference)
findPreference("news_feed");
news2Pref.setEntryValues(getResources().
getStringArray(R.array.newsfeed));
news2Pref.setDefaultValue(1);
}
}
}
you need to add onPreferenceChangeListener like below...
final CheckBoxPreference checkboxPref = (CheckBoxPreference) getPreferenceManager().findPreference("french");
checkboxPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if(newValue.toString().equals("true") {
// add your code here if checkbox is checked.
}
else {
// add your code here if checkbox is not checked.
}
return true;
}
});
Method setDefaultValue() takes an Object as argument, rather than index in values array. So, you should rewrite your code something like this:
String[] values = getResources().getStringArray(R.array.newsfeed)
news2Pref.setEntryValues(values);
news2Pref.setDefaultValue(values[0]);
Moreover, you should probably set entry titles too:
news2Pref.setEntries(your_titles_array_here);
Related
Is there any reason why the onPreferenceChange for a ListPreference method isn't called when you use setValue(...) method?
The only time the onPreferenceChange is called is when I physically touch the ListPreference and make a selection. But when I programmatically change the value of the ListPreference, it doesn't get called.
Here's my setOnPreferenceChangeListener method definition:
public class SettingsActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
...
// Load the preferences.xml
addPreferencesFromResource(R.xml.preferences);
// Set the summary for each Preference by reading its defaultValue
PreferenceManager.setDefaultValues(getApplicationContext(), R.xml.preferences, false);
// Define a change listener
final String ORIENTATION_KEY = mResources.getString(R.string.pref_quick_orientation_key);
ListPreference preference = (ListPreference) findPreference(ORIENTATION_KEY);
preference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object o) {
// Do something here...
return true;
}
});
...
// Somewhere else in my code, using this code to change the value of the Preference
final String ORIENTATION_KEY = mResources.getString(R.string.pref_quick_orientation_key);
ListPreference preference = (ListPreference) findPreference(ORIENTATION_KEY);
preference.setValue(mResources.getString(R.string.orientation_portrait));
...
}
I am currently able to create a preference screen with a PreferenceFragment, in which I assign my preferences using:
addPreferencesFromResource(R.xml.preferences);
Instead of using the resource 'R.xml.preferences', I would like to use my SharedPreferences i have already saved, for example:
SharedPreferences prefs = this.getActivity().getSharedPreferences("preferences", 0);
addPreferencesFromResource(prefs);
However, this does not work. Is it possible to do this? If so, How? Or is it required that I use an xml document?
I happen to had exactly the same problem but I figured it out, hope this helps.
You need to do the following steps in order to add a Custom Preference without using an XML Reouser
First:
You need to create a Preference Screen, this is as it says a "screen" which can containt several Preferences and must be linked to your PreferenceFragment or PreferenceActivity.
Consider the Following PreferenceFragment for example (and consider it is contained in a superior Activity..)
public static class YourPreferenceFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PreferenceScreen p = createPreferences();
this.setPreferenceScreen(p);//Set the PreferenceScreen as the current one on this fragment
//now bind values, notice we use p.findPreference which means whe look into the preferenceScreen Associated with the PreferenceFragment/Activity
bindPreferenceSummaryToValue(p.findPreference("some_key"));
}
}
Now Consider that createPreferences is a method that will return a PreferenceScreen with your custom preferences such as a ListPreference or CheckboxPreference. This is how you really create the preferences and add them into a PreferenceScreen
private PreferenceScreen createPreferences()
{
PreferenceScreen p =
getPreferenceManager().createPreferenceScreen(getActivity());
ListPreference listPref = new ListPreference(getActivity());
listPref.setKey("some_key"); //Refer to get the pref value
CharSequence[] csEntries = new String[]{"Item1","Item2"};
CharSequence[] csValues = new String[]{"1","2"};
listPref.setDefaultValue(-1);
listPref.setEntries(csEntries); //Entries(how you display them)
listPref.setEntryValues(csValues);//actual values
listPref.setDialogTitle("Dialog title");
listPref.setTitle("Title");
listPref.setSummary("Some summary");
p.addPreference(listPref);
return p;
}
Please let me know if this helps
best,
EDIT: Code for bindPreferenceSummaryToValue
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's
// current value.
if (preference instanceof CheckBoxPreference) {
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, PreferenceManager.
getDefaultSharedPreferences(preference.getContext()).
getBoolean(preference.getKey(),false));
} else {
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, PreferenceManager.
getDefaultSharedPreferences(preference.getContext()).
getString(preference.getKey(),""));
}
}
I am trying to fill a ListPreference with the contents of the res/anim folder but I am having a problem it keeps coming up blank, I have a static array of strings to fill it and that works but I need it to be dynamic, I can print the text out in the logcat, its just not populating the list can you help me?
PreferenceActivityMenu.java
CharSequence[] entries = null;
CharSequence[] entryValues = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
SharedPreferences prefs=getPreferences(Context.MODE_PRIVATE);
ListPreference prefListAnim = new ListPreference(this);
listAnim();
prefListAnim.setEntries(entries);
prefListAnim.setEntryValues(entryValues);
}
#Override
public boolean onPreferenceClick(Preference preference) {
// TODO Auto-generated method stub
return false;
}
public void listAnim() {
Field[] fields = R.anim.class.getFields();
entries = new String[fields.length];
entryValues = new String[fields.length];
for (int count = 0; count < fields.length; count++) {
Log.i("Raw Asset: ", fields[count].getName());
entries[count] = fields[count].getName();
entryValues[count] = Integer.toString(count);
}
}
and preference.xml
<PreferenceCategory android:title="Animation Transitions" >
<ListPreference
android:dialogTitle="#string/prefsList_dialogTitle"
android:key="prefList_animations"
android:summary="#string/prefsList_summary"
android:title="#string/prefsList_title" >
</ListPreference>
</PreferenceCategory>
Thanks for your help
You are setting the list data to a different preference than the one declared in xml. Currently you're setting the data against a newly created ListPreference:
ListPreference prefListAnim = new ListPreference(this);
However, you're displaying the (empty) one declared in xml. You should do either one or the other. For example, the easiest solution is probably to change above to inflate the preference from xml in stead:
ListPreference prefListAnim = (ListPreference) findPreference("prefList_animations");
How can I change the view of a CheckBoxPreference at runtime?
Specifically, I'd like to change a CheckBoxPreference summary depending on whether the user has checked the box or not.
If it were a normal view, I could do something like:
view1 = (TextView)findViewById(R.id.idView1);
view1.setText("some text");
But a CheckBoxPreference has no id, so I don't know how to get a "handle" to it.
I have an answer to my own question. The key is to use findPreference in a PreferenceActivity, as follows:
public class MyPreferenceActivity extends PreferenceActivity{
private SharedPreferences preferences;
private SharedPreferences.OnSharedPreferenceChangeListener prefListener;
private CheckBoxPreference pref;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
pref = (CheckBoxPreference) findPreference(res.getString(R.string.keyAccount));
pref.setSummary("something");
//-- preference change listener
prefListener = new SharedPreferences.OnSharedPreferenceChangeListener(){
public void onSharedPreferenceChanged(SharedPreferences prefs, String key){
if (key.equals(somekey)){
pref.setSummary("something new");
}
}
};
preferences.registerOnSharedPreferenceChangeListener(prefListener);
}
This is tested and works.
You should use (in XML layout file):
android:summaryOff
android:summaryOn
You can set id to CheckBoxPreference using android:id in xml like code below
<CheckBoxPreference
android:key="pref_boot_startup"
android:title="Auto start"
android:defaultValue="true"
android:id="#+id/my_CheckBoxPref"
/>
To retrieve you can use
CheckBoxPreference check = (CheckBoxPreference)findViewById(R.id.my_CheckBoxPref);
The XML file of my ListPreference
<ListPreference android:key="lpBirim" android:title="Birim"
android:summary="" android:defaultValue="0" android:persistent="false"/>
How to get the selected text and the selected value?
in your PreferenceActivity do something like:
ListPreference listPreference = (ListPreference) findPreference("lpBirim");
CharSequence currText = listPreference.getEntry();
String currValue = listPreference.getValue();
You can use this snippet to get the value:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.getString("lpBirim","-1")
Have look on the tutorial
Here is an example:
#Override
public boolean onPreferenceChange(Preference preference, Object value)
{
String textValue = value.toString();
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(textValue);
CharSequence[] entries = listPreference.getEntries();
if(index >= 0)
Toast.makeText(preference.getContext(), entries[index], Toast.LENGTH_LONG);
return true;
}
index contains the index of the clicked item
textValue is the Selected Value
entries[index] is the Selected Text
SharedPreferences Preference = PreferenceManager.getDefaultSharedPreferences(this);
Preference.getString("your list preference key","-1")
You can use findPreference() to get a ListPreference that has all methods you need. To have it working you need to use or extend PreferenceFragment first.