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
Related
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
I have a ListPreferenece in my preference screen and when It changes I need to execute a method. Problem is when I first change the preferenece list nothing happens but it works the second time round...
public static class DisplayFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
cPPreference cPBg;
cPPreference cPFt;
cPPreference cPTm;
cPPreference cPLg;
ListPreference colorThemeList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.display_preferences);
cPBg = (cPPreference) getPreferenceScreen().findPreference("ambilBg");
cPFt = (cPPreference) getPreferenceScreen().findPreference("ambilFt");
cPTm = (cPPreference) getPreferenceScreen().findPreference("ambilTm");
cPLg = (cPPreference) getPreferenceScreen().findPreference("ambilLg");
/**
* When this list changes I need to exectue a method
*/
colorThemeList = (ListPreference) getPreferenceScreen().findPreference("colorTheme");
colorThemeList.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
ThemeHandler.setTheme(cPBg, cPFt, cPTm, cPLg, colorThemeList.getValue());
return true;
}
});
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
setSummarys();
}
}
Any help greatly appreciated
O.k ...found solution
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("colorTheme")) {
ThemeHandler.setTheme(colorPickerBg, colorPickerFt, colorPickerTm, colorPickerLg, colorThemeList.getValue());
}
}
A simple check in the onSharedPreferneceChanged method :)
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
getFragmentManager().beginTransaction()
.add(R.id.settingsContainer, new SettingsFragment())
.commit();
}
public static class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("aKey") {
Preference pref = findPreference(key);
pref.setSummary(sharedPreferences.getString(key, ""));
}
}
}
}
When the user changes his preferences they are stored and showed by the listener.
When the activity is restarted I lost all the summaries, but values are correctly stored because they are retrieved if I click on each preference.
I'd like to show what was done before, not default values.
In your onResume() method after registering the listener just call the listener with every preference key.
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
onSharedPreferenceChanged(getPreferenceScreen().getSharedPreferences(), "your_key");
}
when the Fragment was created, you call the following method:
addPreferencesFromResource(R.xml.preferences)
the if the xml file preferences content is stationary, and you change another preference file when accept onSharedPreferenceChanged.
May you can get values with method getActivity().getSharedPreferences().
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;
}
});
I'm trying to implement OnPreferenceClickListener over PrefernceFragment and it seems like the onPreferenceClick() is never called.
I have another PrefernceFragment implementing OnSharedPreferenceChangeListener and it works just fine.
Is this a bug of the OS ? is the OnPreferenceClickListener not supposed to be supported for PrefernceFragment ?
If there is no need to register the fragment as listener as I read, then I really think my code is correct.
public class myClass extends PreferenceFragment implements OnPreferenceClickListener {
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(com.XX.ZZ.R.xml.YY);
}
#Override
public boolean onPreferenceClick(Preference preference) {
// never called.
}
}
PreferenceFragment doesn't have a onPreferenceClick() method. There is really no need to listen for click events since the Android fragment takes care of writing the preference values into memory. If you really need to watch for a click event, you can use findPreference(CharSequence key) to find each of the Preferences you want to watch and then call setOnPreferenceClickListener(this) on those.
You must set preferenceClickListener on your preference.
public class myClass extends PreferenceFragment implements OnPreferenceClickListener {
#Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(com.XX.ZZ.R.xml.YY);
Preference preference = findPreference("myPreference");
preference.setOnPreferenceClickListener(this);
}
#Override
public boolean onPreferenceClick(Preference preference) {
// never called.
}
UPDATE:
If you want to set onPreferenceClickListener to all preferences, you can do it like this:
public class myClass extends PreferenceFragment implements OnPreferenceClickListener {
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.menu.main);
Set<String> preferenceNames = getPreferenceManager().getSharedPreferences().getAll().keySet();
for (String prefName : preferenceNames) {
Preference preference = findPreference(prefName);
preference.setOnPreferenceClickListener(this);
}
}
#Override
public boolean onPreferenceClick(Preference preference) {
// or get preference.getKey() to select based on preference names
switch (preference.getOrder()) {
case 0:
return true;
case 1:
return true;
default:
return false;
}
}
}