Создание страницы настроек в Android Studio

Убедитесь, что в build.gradle (app) добавлены зависимости:

dependencies {
    implementation 'androidx.preference:preference:1.2.1'
}

Создайте XML файл настроек

Создайте файл res/xml/root_preferences.xml

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <SwitchPreferenceCompat
        android:key="notifications"
        android:title="Уведомления"
        android:summary="Включить или выключить уведомления"
        android:defaultValue="true" />

    <EditTextPreference
        android:key="username"
        android:title="Имя пользователя"
        android:summary="Укажите своё имя"
        android:defaultValue="Гость" />

    <ListPreference
        android:key="theme"
        android:title="Тема"
        android:summary="Выберите тему оформления"
        android:entries="@array/theme_names"
        android:entryValues="@array/theme_values"
        android:defaultValue="light" />

</PreferenceScreen>

Также создайте массивы тем в res/values/arrays.xml

<resources>
    <string-array name="theme_names">
        <item>Светлая</item>
        <item>Тёмная</item>
    </string-array>
    <string-array name="theme_values">
        <item>light</item>
        <item>dark</item>
    </string-array>
</resources>

Создайте Fragment настроек

Создайте SettingsFragment.java

import android.os.Bundle;
import androidx.preference.PreferenceFragmentCompat;

public class SettingsFragment extends PreferenceFragmentCompat {
    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.root_preferences, rootKey);
    }
}

Создайте слой для фрагмента

Разметка res/layout/settings_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/settings_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Создайте Activity для отображения настроек

Создайте SettingsActivity.java

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

public class SettingsActivity extends AppCompatActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.settings_activity);

    getSupportFragmentManager()
      .beginTransaction()
      .replace(android.R.id.setting_container, new SettingsFragment())
      .commit();
  }
}

Разметка res/layout/settings_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/settings_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Добавьте Activity в AndroidManifest.xml

<activity android:name=".SettingsActivity"
   android:label="Настройки"
   android:exported="true" />

Работа с настройками

Открытие страницы настроек из меню

Например, в MainActivity:

Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);

Как получить значение из настроек

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean notificationsEnabled = sharedPreferences.getBoolean("notifications", true);
String username = sharedPreferences.getString("username", "Гость");

Оцените статью
Добавить комментарий