findPreference<SwitchPreferenceCompat>("notifications")?.setOnPreferenceChangeListener{_,newValue->Log.d("Preferences","Notifications enabled: $newValue")true// Return true if the event is handled.}findPreference<Preference>("feedback")?.setOnPreferenceClickListener{Log.d("Preferences","Feedback was clicked")true// Return true if the click is handled.}
Java
SwitchPreferenceCompatnotificationsPref=findPreference("notifications");if(notificationsPref!=null){notificationsPref.setOnPreferenceChangeListener((preference,newValue)->{Log.d("Preferences",String.format("Notifications enabled: %s",newValue));returntrue;// Return true if the event is handled.});}PreferencefeedbackPref=findPreference("feedback");if(feedbackPref!=null){feedbackPref.setOnPreferenceClickListener((preference)->{Log.d("Preferences","Feedback was clicked");returntrue;// Return true if the event is handled.});}
[null,null,["最后更新时间 (UTC):2025-07-26。"],[],[],null,["# Settings\nPart of [Android Jetpack](/jetpack).\n=============================================\n\nSettings let users change the functionality and behavior of an app. Settings can\naffect background behavior, such as how often the app synchronizes data with the\ncloud, or they can be wider-reaching, such as changing the contents and\npresentation of the user interface.\n| **Note:** This document explains how to use the [AndroidX Preference\n| library](/reference/androidx/preference/package-summary). Starting with Android 10, the platform `android.preference` library is deprecated.\n\nTo integrate user configurable settings into your app, use the AndroidX\nPreference library. This library manages the user interface and interacts with\nstorage so that you define only the individual settings that the user can\nconfigure. The library comes with a Material Design theme that provides a\nconsistent user experience across devices and OS versions.\n\nGet started\n-----------\n\nA [`Preference`](/jetpack/androidx/releases/preference) is the basic building\nblock of the Preference library. A settings screen contains a `Preference`\n*hierarchy* . You can define this hierarchy as an XML resource, or you can [build\na hierarchy in code](/guide/topics/ui/settings/programmatic-hierarchy).\n\nThe following sections describe how to build a simple settings screen using the\nAndroidX Preference library.\n\nBefore you start, add the Preference library dependency to your `build.gradle`\nfile: \n\n### Groovy\n\n```groovy\ndependencies {\n implementation \"androidx.preference:preference-ktx:1.2.0\"\n}\n```\n\n### Kotlin\n\n```kotlin\ndependencies {\n implementation(\"androidx.preference:preference-ktx:1.2.0\")\n}\n```\n\nAfter a Gradle Sync, you can move on to the XML part of the task.\n\n### Create a hierarchy\n\nIn your project, navigate to `res/xml` folder, create a `preferences.xml` file,\nand add the following code to it: \n\n```xml\n\u003cPreferenceScreen\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\u003e\n\n \u003cSwitchPreferenceCompat\n app:key=\"notifications\"\n app:title=\"Enable message notifications\"/\u003e\n\n \u003cPreference\n app:key=\"feedback\"\n app:title=\"Send feedback\"\n app:summary=\"Report technical issues or suggest new features\"/\u003e\n\n\u003c/PreferenceScreen\u003e\n```\n\nThis hierarchy contains two `Preference` objects: a\n[`SwitchPreferenceCompat`](/reference/androidx/preference/SwitchPreferenceCompat)\nthat lets users toggle a setting on and off, and a basic `Preference` with no\nwidget.\n\nWhen building a hierarchy, each `Preference` must have a unique key.\n| **Note:** See the [Android Settings Design\n| Guidelines](https://source.android.com/devices/tech/settings/settings-guidelines) for recommendations on how to organize your settings screen.\n\n### Inflate the hierarchy\n\nTo inflate a hierarchy from an XML attribute, create a\n[`PreferenceFragmentCompat`](/reference/androidx/preference/PreferenceFragmentCompat),\noverride\n[`onCreatePreferences()`](/reference/androidx/preference/PreferenceFragmentCompat#oncreatepreferences),\nand provide the XML resource to inflate, as shown in the following example: \n\n### Kotlin\n\n```kotlin\nclass MySettingsFragment : PreferenceFragmentCompat() {\n override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {\n setPreferencesFromResource(R.xml.preferences, rootKey)\n }\n}\n```\n\n### Java\n\n```java\npublic class MySettingsFragment extends PreferenceFragmentCompat {\n @Override\n public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {\n setPreferencesFromResource(R.xml.preferences, rootKey);\n }\n}\n```\n\nYou can then add this `Fragment` to your `Activity` as you do with any other\n`Fragment`: \n\n### Kotlin\n\n```kotlin\nclass MySettingsActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n supportFragmentManager\n .beginTransaction()\n .replace(R.id.settings_container, MySettingsFragment())\n .commit()\n }\n}\n```\n\n### Java\n\n```java\npublic class MySettingsActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n getSupportFragmentManager()\n .beginTransaction()\n .replace(R.id.settings_container, new MySettingsFragment())\n .commit();\n }\n}\n```\n\nThe result is shown in the following image:\n**Figure 1.** A settings screen created using two `Preference` objects.\n\n\u003cbr /\u003e\n\nMonitor the preferences\n-----------------------\n\nYou can get an event when a preference changes by registering a listener for\nit: \n\n### Kotlin\n\n```kotlin\nfindPreference\u003cSwitchPreferenceCompat\u003e(\"notifications\")\n ?.setOnPreferenceChangeListener { _, newValue -\u003e\n Log.d(\"Preferences\", \"Notifications enabled: $newValue\")\n true // Return true if the event is handled.\n }\n\nfindPreference\u003cPreference\u003e(\"feedback\")\n ?.setOnPreferenceClickListener {\n Log.d(\"Preferences\", \"Feedback was clicked\")\n true // Return true if the click is handled.\n }\n```\n\n### Java\n\n```java\nSwitchPreferenceCompat notificationsPref = findPreference(\"notifications\");\n\nif (notificationsPref != null) {\n notificationsPref.setOnPreferenceChangeListener((preference, newValue) -\u003e {\n Log.d(\"Preferences\", String.format(\"Notifications enabled: %s\", newValue));\n return true; // Return true if the event is handled.\n });\n}\n\nPreference feedbackPref = findPreference(\"feedback\");\n\nif (feedbackPref != null) {\n feedbackPref.setOnPreferenceClickListener((preference) -\u003e {\n Log.d(\"Preferences\", \"Feedback was clicked\");\n return true; // Return true if the event is handled.\n });\n}\n```\n\nRead the current preference value\n---------------------------------\n\n`PreferenceFragmentCompat` hides much of the machinery involved in saving and\nreading the preferences. However, everything is stored using\n`SharedPreferences`, and you can read these values as you normally do with\n`SharedPreferences`: \n\n### Kotlin\n\n```kotlin\nval preferences = PreferenceManager.getDefaultSharedPreferences(this).all\n\npreferences.forEach {\n Log.d(\"Preferences\", \"${it.key} -\u003e ${it.value}\")\n}\n```\n\n### Java\n\n```java\nvar preferences = PreferenceManager.getDefaultSharedPreferences(context).getAll();\n\npreferences.forEach((key, value) -\u003e{\n Log.d(\"Preferences\", String.format(\"%s -\u003e %s\", key, value));\n});\n```\n\nThe previous snippet obtains an instance of the default `SharedPreferences` for\nthe app, accesses all the stored values, loops over them, and prints them in\nLogcat."]]