PreferenceFragmentCompat
Android’s SharedPreferences interface provides a means of privately storing and retrieving key-value data separately for each app installed on a device. This data persists across launches and is purged on uninstall. PreferenceFragmentCompat can be used in place of the Fragment class in activities and in navigation to provide a light-weight UI for viewing and updating those SharedPreferences key-values.
The UI illustrated above may either be inflated from an XML document, or built in code. To inflate a PreferenceScreen from XML, first create a layout file with the <PreferenceScreen> tag as its root element. This layout file is stored under the src/main/res/xml directory of a module in Android projects.
Inside the onCreatePreferences function of your PreferenceFragmentCompat subclass, call setPreferencesFromResource to load the layout and perform inflation. In terms of fragment lifecycle, setPreferencesFromResource will be called via the superclass’s onCreate function.
Which means that any time there’s a configuration change (e.g. rotation of the device), the PreferenceScreen needs to be recreated. Most of the code in the following SettingsFragment.kt example is dedicated to updating the preference summaries, either because of a device configuration change, or because of changes to the preference values via user interaction.
To build a hierarchy from code, use PreferenceManager.createPreferenceScreen(Context) to create the root PreferenceScreen. Once you have added other Preference objects to this root screen with PreferenceGroup.addPreference(Preference), you then need to set the screen as the root screen in your hierarchy with setPreferenceScreen(PreferenceScreen).
An example project illustrating some of these techniques can be found here.