Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a Preference with a SummaryProvider in a PreferenceFragmentCompat?

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.

like image 984
Zardoz Avatar asked Jun 12 '19 20:06

Zardoz


People also ask

What is Androidx preference?

The Preference library allows you to build interactive settings screens, without needing to handle interacting with device storage or managing the user interface.

What is Preference fragment?

In Android apps, there are often settings pages that contain different options the user can tweak. The PreferenceFragment and PreferenceFragmentCompat contains a hierarchy of preference objects displayed on screen in a list. These preferences will automatically save to SharedPreferences as the user interacts with them.


1 Answers

    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>
like image 82
VasilisK Avatar answered Sep 19 '22 22:09

VasilisK