Как создать экран настроек в приложении для Android? - PullRequest
0 голосов
/ 23 марта 2019

Как мне создать экран настроек? Должен ли я использовать PreferenceActivity или PreferenceFragment ?

Примечание- Документация не помогла

Что я уже пробовал:

  1. Использование PreferenceActivity , но не удалось реализовать в нем простую панель инструментов.
  2. Использование PreferenceFragment , но было слишком сложным для понимания.

Мне нужна простая реализация, использующая PreferenceFragment

Ответы [ 2 ]

4 голосов
/ 23 марта 2019

Вот полный рабочий код для реализации настроек в Android:

добавить эту библиотеку в ваш проект

implementation 'androidx.preference:preference:1.1.0-alpha02'

  • Создать НастройкиActivity и добавить его в Манифест

    <activity android:name=".SettingsActivity"/>
    

activity_preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/color_primary"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

            <TextView
                android:id="@+id/toolbar_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="Settings"
                android:textAppearance="@style/TextAppearance.Widget.AppCompat.Toolbar.Title"
                android:textColor="@android:color/white"
                android:textSize="16sp" />
        </androidx.appcompat.widget.Toolbar>


    </com.google.android.material.appbar.AppBarLayout>


    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />


</androidx.coordinatorlayout.widget.CoordinatorLayout>

SettingsActivity

public class SettingsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preferences);
        Toolbar toolbar = findViewById(R.id.toolbar);
        try {
            setSupportActionBar(toolbar);
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.setDisplayShowTitleEnabled(false);
                actionBar.setDisplayHomeAsUpEnabled(true);
                actionBar.setDisplayShowHomeEnabled(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        getSupportFragmentManager().beginTransaction().replace(R.id.container, new SettingsFragment()).commit();
    }
}

SettingsFragment

public class SettingsFragment extends PreferenceFragmentCompat {
    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String s) {
        addPreferencesFromResource(R.xml.preferences);
        // implement your settings here
    }
}

preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.preference.PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android">

    <androidx.preference.PreferenceCategory android:title="General Settings">

        <androidx.preference.Preference
            android:key="general_settings_key"
            android:title="Preference Test" />

        <androidx.preference.SwitchPreferenceCompat
            android:defaultValue="true"
            android:key="switch_settings_key"
            android:title="Switch" />

    </androidx.preference.PreferenceCategory>


    <androidx.preference.PreferenceCategory android:title="Other">

        <androidx.preference.Preference
            android:key="about_settings_key"
            android:title="About Me" />


    </androidx.preference.PreferenceCategory>


</androidx.preference.PreferenceScreen>
  • Запустить настройки активности и теста
2 голосов
/ 23 марта 2019

В Android 3.0 и более поздних версиях вы должны использовать PreferenceFragment, который отображает настройки вашего приложения.

Создать фрагмент настроек:

public static class SettingsFragment extends PreferenceFragment {
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      // Load the preferences from an XML resource
      addPreferencesFromResource(R.xml.preferences);
   }
   ...
}

И показать его в своей деятельности, как и любой другой фрагмент:

public class SettingsActivity extends Activity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_settings);
      // Display the fragment as the main content.
      getFragmentManager().beginTransaction()
                .replace(android.R.id.content, new SettingsFragment())
                .commit();
   }
}

Вы можете включить панель инструментов в xml своей деятельности и добавить в нее контейнер для SettingsFragment, таким образом, будут отображаться панель инструментов и ваш SettingsFragment)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_catalog_root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="-20dp">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/fragment_catalog_first_appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#00000000"
        app:elevation="0dp"
        >

        <androidx.appcompat.widget.Toolbar
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/fragment_catalog_first_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/transparent_background"
            android:elevation="4dp"
            >

        </androidx.appcompat.widget.Toolbar>

    </com.google.android.material.appbar.AppBarLayout>

    <FrameLayout
        android:id="@+id/activity_catalog_fragment_cont"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="?android:attr/actionBarSize"
        android:animateLayoutChanges="true"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</RelativeLayout>

Если вы не используете androidx (но вам лучше использовать), вы можете использовать панель инструментов в своем XML-файле, например:

<android.support.v7.widget.Toolbar.....>

Обратите внимание: вам нужно использовать атрибут android:layout_marginTop="?android:attr/actionBarSize" (или если вы 'Использование библиотеки AppCompat: ?attr/actionBarSize) для вашего контейнера фрагментов появится под панелью инструментов

В рамках своей деятельности не забудьте переопределить метод onClick () для вашей панели инструментов:

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
       getActivity().onBackPressed();
    }
});
...