تنظیمات به کاربران امکان می دهد عملکرد و رفتار یک برنامه را تغییر دهند. تنظیمات میتوانند بر رفتار پسزمینه تأثیر بگذارند، مانند تعداد دفعاتی که برنامه دادهها را با ابر همگامسازی میکند، یا میتوانند گستردهتر باشند، مانند تغییر محتویات و ارائه رابط کاربری.
برای ادغام تنظیمات قابل پیکربندی کاربر در برنامه خود، از کتابخانه ترجیحی AndroidX استفاده کنید. این کتابخانه رابط کاربری را مدیریت میکند و با فضای ذخیرهسازی تعامل میکند، به طوری که شما فقط تنظیمات فردی را که کاربر میتواند پیکربندی کند، تعریف کنید. این کتابخانه با موضوع طراحی مواد ارائه میشود که تجربه کاربری ثابتی را در دستگاهها و نسخههای سیستمعامل ارائه میدهد.
شروع کنید
یک Preference بلوک اصلی ساختمان کتابخانه Preference است. صفحه تنظیمات حاوی یک سلسله مراتبPreference است. شما می توانید این سلسله مراتب را به عنوان یک منبع XML تعریف کنید، یا می توانید یک سلسله مراتب را در کد ایجاد کنید .
بخشهای زیر نحوه ساخت یک صفحه تنظیمات ساده با استفاده از کتابخانه ترجیحی AndroidX را شرح میدهند.
قبل از شروع، وابستگی کتابخانه Preference را به فایل build.gradle خود اضافه کنید:
این سلسله مراتب شامل دو شیء Preference است: یک SwitchPreferenceCompat که به کاربران امکان می دهد تنظیمات را روشن و خاموش کنند، و یک Preference اصلی بدون ویجت.
هنگام ساخت یک سلسله مراتب، هر Preference باید یک کلید منحصر به فرد داشته باشد.
سلسله مراتب را متورم کنید
برای افزایش یک سلسله مراتب از یک ویژگی XML، یک PreferenceFragmentCompat ایجاد کنید، onCreatePreferences() را لغو کنید و منبع XML را برای inflate فراهم کنید، همانطور که در مثال زیر نشان داده شده است:
نتیجه در تصویر زیر نشان داده شده است: شکل 1. صفحه تنظیمات ایجاد شده با استفاده از دو شیء Preference .
بر ترجیحات نظارت کنید
با ثبت یک شنونده برای آن، می توانید رویدادی را هنگامی که یک اولویت تغییر می کند، دریافت کنید:
کاتلین
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.}
جاوا
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.});}
مقدار ترجیحی فعلی را بخوانید
PreferenceFragmentCompat بسیاری از ماشین آلات مربوط به ذخیره و خواندن تنظیمات برگزیده را پنهان می کند. با این حال، همه چیز با استفاده از SharedPreferences ذخیره میشود و میتوانید این مقادیر را همانطور که معمولاً با SharedPreferences انجام میدهید بخوانید:
قطعه قبلی نمونه ای از SharedPreferences پیش فرض را برای برنامه به دست می آورد، به تمام مقادیر ذخیره شده دسترسی پیدا می کند، روی آنها حلقه می زند و آنها را در Logcat چاپ می کند.
محتوا و نمونه کدها در این صفحه مشمول پروانههای توصیفشده در پروانه محتوا هستند. جاوا و OpenJDK علامتهای تجاری یا علامتهای تجاری ثبتشده Oracle و/یا وابستههای آن هستند.
تاریخ آخرین بهروزرسانی 2025-07-29 بهوقت ساعت هماهنگ جهانی.
[[["درک آسان","easyToUnderstand","thumb-up"],["مشکلم را برطرف کرد","solvedMyProblem","thumb-up"],["غیره","otherUp","thumb-up"]],[["اطلاعاتی که نیاز دارم وجود ندارد","missingTheInformationINeed","thumb-down"],["بیشازحد پیچیده/ مراحل بسیار زیاد","tooComplicatedTooManySteps","thumb-down"],["قدیمی","outOfDate","thumb-down"],["مشکل ترجمه","translationIssue","thumb-down"],["مشکل کد / نمونهها","samplesCodeIssue","thumb-down"],["غیره","otherDown","thumb-down"]],["تاریخ آخرین بهروزرسانی 2025-07-29 بهوقت ساعت هماهنگ جهانی."],[],[],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."]]