설정을 통해 사용자는 앱의 기능과 동작을 변경할 수 있습니다. 설정에서
백그라운드 동작에 영향을 미칩니다. 즉, 앱이 데이터를
콘텐츠를 변경하는 등 더 폭넓게 제공될 수도 있습니다.
자세히 살펴보겠습니다.
사용자가 구성 가능한 설정을 앱에 통합하려면 AndroidX를 사용합니다.
환경설정 라이브러리. 이 라이브러리는 사용자 인터페이스를 관리하고
사용자가 스토리지에 액세스하여 관리할 수 있는
구성합니다 이 라이브러리에는 머티리얼 디자인 테마가 있어
여러 기기와 OS 버전에서
일관된 사용자 경험을 제공합니다
시작하기
Preference은 기본 건물입니다.
환경설정 라이브러리의 블록입니다. 설정 화면에는 Preference가 포함되어 있습니다.
계층 구조. 이 계층 구조를 XML 리소스로 정의하거나
계층 구조입니다.
다음 섹션에서는
AndroidX 환경설정 라이브러리
시작하기 전에 build.gradle에 Preference 라이브러리 종속 항목을 추가합니다.
파일:
다음에 대한 리스너를 등록하여 환경설정이 변경될 때 이벤트를 가져올 수 있습니다.
다음과 같습니다.
Kotlin
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 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-07-26(UTC)
[[["이해하기 쉬움","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-26(UTC)"],[],[],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."]]