Settings Part of Android Jetpack.
Settings allow users to change the functionality and behavior of an application. Settings can affect background behavior, such as how often the application synchronizes data with the cloud, or they can be more wide-reaching, such as changing the contents and presentation of the user interface.
The recommended way to integrate user configurable settings into your application is to use the AndroidX Preference Library. This library manages the user interface and interacts with storage so that you define only the individual settings that the user can configure. The library comes with a Material theme that provides a consistent user experience across devices and OS versions.
Getting started
A Preference
is the basic building block of the Preference Library. A settings
screen contains a Preference
hierarchy. You can define this hierarchy as an
XML resource, or you can build a hierarchy in code.
The sections below describe how to build a simple settings screen using the AndroidX Preference Library.
Create a hierarchy
The following example shows a simple hierarchy that is defined via XML:
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto"> <SwitchPreferenceCompat app:key="notifications" app:title="Enable message notifications"/> <Preference app:key="feedback" app:title="Send feedback" app:summary="Report technical issues or suggest new features"/> </PreferenceScreen>
This hierarchy contains two individual Preferences
: a
SwitchPreferenceCompat
that allows a user to toggle a setting on or off, and a basic Preference
with
no widget.
When building a hierarchy, each Preference
should have a unique key.
Inflate the hierarchy
To inflate a hierarchy from an XML attribute, create a
PreferenceFragmentCompat
,
override
onCreatePreferences()
,
and provide the XML resource to inflate, as shown in the example below:
Kotlin
class MySettingsFragment : PreferenceFragmentCompat() { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.preferences, rootKey) } }
Java
public class MySettingsFragment extends PreferenceFragmentCompat { @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { setPreferencesFromResource(R.xml.preferences, rootKey); } }
You can then add this Fragment
to your Activity
as you would with any other
Fragment
:
Kotlin
class MySettingsActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) supportFragmentManager .beginTransaction() .replace(R.id.settings_container, MySettingsFragment()) .commit() } }
Java
public class MySettingsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportFragmentManager() .beginTransaction() .replace(R.id.settings_container, new MySettingsFragment()) .commit(); } }