Reputation: 16627
In androidx.preference.Preference
(using Version 1.1.0-beta01) it is possible to set a summary provider, which I did inside the onCreatePreferences
method of a PreferenceFragmentCompat
.
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
...
val mySummaryProvider = Preference.SummaryProvider<Preference> {
val str = preferenceManager.sharedPreferences.getString(it.key, "")
doSomethingCool(str)
}
findPreference<Preference>("my_pref_id").summaryProvider = mySummarProvider
}
When I now update the preference (by using the preference editor) while the fragment is still visible, how do I notify the preference or the fragment that the summary provider should be called again (it isn't done automatically)? Unfortunately, I don't see any method or way to do that.
Upvotes: 12
Views: 3621
Reputation: 6222
I am having a bit trouble to understand the issue, but I would use setSummaryProvider only to update the summary and use a ChangeListener to update other stuff:
with(findPreference<ListPreference>(PREFKEY_DOWNLOAD_SERVER)!!) {
setSummaryProvider { pref ->
getString(R.string.pref_download_server_summary, (pref as ListPreference).value)
}
setOnPreferenceChangeListener { _, newValue -> DataLoader.setSelectedServer(newValue as String); true }
}
Upvotes: 0
Reputation: 87
public class SettingsClass extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.settings_prefs);
final SwitchPreferenceCompat switchPreferenceCompat = (SwitchPreferenceCompat) getPreferenceManager().findPreference("rememberME");
switchPreferenceCompat.setSummaryProvider(new Preference.SummaryProvider() {
@Override
public CharSequence provideSummary(Preference preference) {
if (switchPreferenceCompat.isChecked()) {
return "Active";
}
return "Inactive";
}
});
}}
//.xml file
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:key="test">
<PreferenceCategory android:title="Σύνδεση">
<SwitchPreferenceCompat
app:key="rememberME"
android:defaultValue="false"
app:title="Παραμείνετε Συνδεδεμένος" />
</PreferenceCategory>
</PreferenceScreen>
Upvotes: 4
Reputation: 514
SummaryProvider
is mostly intended to be used for updating the summary of a preference after it updates itself, such as when an option in a ListPreference
is selected, forcing an update of the Preference
and hence triggering the SummaryProvider
.
If you are typically changing the data underneath the preference, do you need a SummaryProvider
here? If not, you could just manually call setSummary
when you change the data, since Preferences
currently don't observe their backing data source. It's hard to tell without more sample code, but it seems strange that the data can change without the user's input, while they are currently viewing the preferences.
Upvotes: 2