Android preferences about screen

Implementing Preferences Settings Screen in Android

There are certain situations when you want to have some kind of Settings in your application apart from the Android default Settings. For example, if you want to increase the text size of the text present in your application and not to increase the text size of all the applications present in the mobile device. Other examples include taking the current address of the user or setting the notification sound to a particular ringtone of your own choice. In order to use this functionality in our application, we can use the feature of Settings which is a part of Android Jetpack.

Settings allow the users to change the behavior and functionality of a particular application instead of changing the behavior and functionality of all the applications present in the mobile device. Also, the users don’t access the Settings frequently, because they change the Settings once and they rarely need to go back and change it again.

Also, the user prefers to change the settings of the application by clicking on the Settings present inside navigation or is present in the menu item like below:

Image Courtesy: Android Codelabs

If you are putting this Setting option anywhere in the application apart from the above mentioned two places, then it will result in bad user experience.

In this blog, we will learn how to implement Preference Settings in our application to change the behavior of our application. So, let’s get started.

Creating a project with the Settings option

Android Studio provides a shortcut for using the Settings feature in the menu item of your application. All you have to do is create a new project in Android Studio with Basic Activity template (not Empty Activity). The Basic Activity template includes a Setting option in the menu and a floating action button as shown below:

Another way of creating a Setting Activity is to go to your Java/Kotlin code folder in your Android project and then right click > new > Activity > Settings Activity. By adding a Settings Activity, you will be given three options as below:

Here you will get options like:

  • General: You can change the Display name. Other options available here are: Enable social recommendations and Add friends to messages.
  • Notification: Here you will we give with options to change the Ringtone of the notification along with vibrate option.
  • Data & sync: Here you will find an option to set the sync frequency of your application.

If your application needs one or all the above three mentioned features, then you can add a Settings Activity, but if you want some customized settings in your application, then you should be using the first option of using the Settings option in your application by creating a Basic Activity. In this blog, we will look at how to implement the Settings by using the Basic Activity.

Adding xml for Settings

Till now, we have added the Settings options in our application by using the Basic Activity. You can manually add the Settings option in the menu item in your application. Now, our next step is to add the UI for the Settings i.e. the UI of the page that will be opened after clicking on the Settings option.

Navigate to the res folder and add an XML directory if not present with name xml. Now, in the res/xml folder, create an xml file named preference_main.xml. Here in the preference_main.xml, we will add the options that will be shown to us when we click on the Settings option.

In the preference_main.xml file, we can add the below properties:

  • EditTextPreference: This is same as a normal EditText that can be used to collect some data from the user. It can be the name of the user or the name of the directory of the application where the user is storing some data of the app.
  • CheckBoxPreference: This is used to select more than one option at a time. One example of this can be checking the option of file uploading using wifi as well as the cellular data.
  • RingtonePreference: This can be used to change the ringtone of the notification that comes from the application. This option is also present in the default Settings Activity.
  • SwitchPreference: This is used to turn on or turn off a certain service in the application. One example of this can be turning the vibration on and off.
  • Preference: To add some TextView that is not clickable or to use the TextView to open into the browser, then you can use preference.
  • List Preference: This can be used to display a list of items and you can choose one of them.

Before moving on to the xml code, you should know the concept of PreferenceScreen and PreferenceCategory.

In the PreferenceScreen tag, all the preferences will be present i.e. it holds all the preferences that you are having in your application.

In the PrefernceCategory tag, you divide your preferences in a certain category and then display them together. For example, you can put the preferences for altering the media of an application in one category and about section in another category. This is the same as using categories in Navigation Drawer. This will help the user to have a clear vision of the functionality of the application.

In the above image, the Screen related settings are put in one category and the System Font and System are put into some other category.

Now, let’s add the Preferences in our application:

In order to add the ListPrefernce in your activity, you have to declare an array that can be displayed in the list.

Now to have the same UI for devices of different screen size and to have proper functioning of Settings in our application, make a class called AppCompatPreference.kt:

Now we have to write the code to handle all the activities of Settings activity. Write the below code that corresponds to various activities of teh Settings Activity:

Finally connect your Settings Activity with the Settings option present in the menu item of MainActivity. Use the below code:

Run the application and try to explore the various options present on the Settings options. Also, try to add some more functionalities to the Settings Activity.

Читайте также:  Istunt 2 для андроид

To learn more about the Settings Preferences in Android, go to the official website of Android Developer.

Источник

Полный список

— используем в настройках список
— группируем настройки по экранам и категориям

На прошлом уроке мы узнали, как несложно создается экран настроек, и использовали там чекбокс и поле для ввода. Немного расширим наши знания и используем новые компоненты:

список (ListPreference) – позволяет выбрать значение из нескольких возможных

экран (PreferenceScreen) – с его помощью можно делать вложенные экраны с настройками

категория (PreferenceCategory) – группировка нескольких настроек

Создадим простое приложение. На первом экране будем читать и отображать значение из настройки-списка. Второй экран будет отображать все настройки.

Project name: P0721_PreferencesSimple2
Build Target: Android 2.3.3
Application name: PreferencesSimple2
Package name: ru.startandroid.develop.p0721preferencessimple2
Create Activity: MainActivity

Мы создали два массива, чуть позже их используем для списка значений.

Рисуем основной экран main.xml:

Здесь только текстовое поле.

Создадим xml-файл с настройками res/xml/pref.xml:

Создавать его, конечно, можно не только через xml, но и конструктором. Вот такая получается картинка:

У нас в настройках будет чекбокс (chb), список (list) и вложенный экран (screen). Внутри screen две категории (categ 1 и categ2), а в них просто чекбоксы. Все просто и понятно.

Из интересного стоит отметить аттрибуты entries и entryValues у ListPreference. entries – это то, что отобразит список пользователю, а entryValues – это то, что сохранит система после выбора значения в списке. Мы используем тут два разных массива. В итоге список покажет значения one, two, three, а сохранит соответственно 1,2 или 3. Можно использовать один массив в обоих атрибутах, тогда отображаемые и сохраняемые значения будут равны.

Создаем Activity для настроек – PrefActivity.java:

В onCreate получаем доступ к настройкам.

В onResume выводим в tvInfo значение из настроек, которое записал туда список. Если значений нет, то пишем текст «не выбрано»

В onCreateOptionsMenu создаем пункт меню и вешаем на него Intent, который запустит нам экран настроек.

Остальные параметры читать не буду, это мы на прошлом уроке рассмотрели, там все просто.

Все сохраним и запустим.

Изначально настройки пусты, в списке ничего не было выбрано.

Переходим через меню на экран настроек.

Первый пункт – чекбокс, второй – список, третий – вложенный экран.

Нажмем на список:

Показаны значения из списка entries. Выбираем устраивающее нас значение, список закрывается и сохраняется соответствующее значение из списка entry_values. Можно вернуться на первый экран кнопкой Назад (Back) и убедиться в этом.

Я выбрал two, сохранилось 2.

Снова идем в экран настроек и жмем на вложенный экран Screen. Провалились внутрь.

Тут куча чекбоксов, которые сгруппированы по двум категориям.

Теперь мы умеем создавать экраны настроек с группировкой элементов по категориям и подэкранам. Это значительно удобнее для пользователя, чем куча разных настроек на одном экране.

На следующем уроке:

— управляем активностью настроек (setEnabled)

Присоединяйтесь к нам в Telegram:

— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.

— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование

— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня

— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме

Источник

Exploring Android Jetpack: Preferences

Settings screens provide a way for our users to configure our application for the way in which they want it to look, feel and behave. As well as this, it’s also a great place for us to provide links to external information such as privacy policies, open-source licences and more. Whilst we can build these screens ourselves, there can often be a lot of boilerplate for what seems like such a simple requirement. Not only do we need to create the user interface, we also need to create the logic used to read and write the values from our application preferences file.

Luckily, Android Jetpack houses what is known as the Preference Library. This provides us with a way to create our application preferences with minimal work from the developers side. Using this Preferences functionality from Android jetpack can not only help you to save development time, but it means that our settings screen will have a consistent material look and feel that ties in with the rest of our application.

Let’s take a dive into Preferences so that we can see what is available and how we can implement it into our applications.

Note: The current release of the Preferences library is androidx.preference:preference:1.1.0-rc01.

Setting up a Preferences screen

In order to build a preferences screen, we have what is known as the Preference hierarchy. This hierarchy is used to defined the different preferences properties that can be can be set for our application. There are two ways which we can define this hierarchy, programmatically or within XML. The way in which we load our settings into the corresponding component (say, a fragment) will depend on how we initially define our hierarchy.

Let’s start by building this settings hierarchy. If we are going to create our preferences via an XML resource then we need to begin by defining a new PreferenceScreen resource within the res/xml directory of our app. Within this we can then define the different preferences that we want to display on this screen.

Within the body of this, we need to define the different settings that we wish to display within the preferences screen. If we’re creating preferences programatically then then go directly into the component (fragment) that we are going to be using for our screen.

Now, there are many different types of settings that can be used, but we’ll start with the simplest of them all which is a simple text item.

You’ll notice here that we define three attributes for our Preference item:

  • key: This key is used to reference the preference value that is saved. This key will be used for the saving and retrieval of our preferences value
  • title: The title used for the display of the preference
  • summary: The description used to display on the preference

And when displayed on screen, we get something that simply looks like this:

If we are creating the Preference programatically, then we achieve this by instantiating a new instance of the Preference class:

Here we can see our preference title displayed in the form of “Basic preference”, along with the corresponding summary, “This is a summary”, displayed underneath it. We can expand on the above by making use of the icon attribute on our Preference item, this allows us to use a drawable reference to display an icon at the start of our preference item:

If we are creating the preference programatically, then we achieve this by setting the icon attribute with our Preference class instance:

Читайте также:  Обои ворлд оф танк для андроида

In some cases, our preference title might expand across more than a single line. This could be in the case where our user is on a smaller device that expected, their text size has been enlarged via the system properties or even our preference title is just too long!

When this is the case, we may wish to fix our setting title to a single line — this can be done by using the singleLineTitle attribute:

If we are creating this preference programatically, then we can again achieve this assigning this property for the instance of our Preference class:

Widget preference items

As well as simple text preference items, the Preferences API provides us with a collection of widget based preferences that can be used to configure the different settings items found within our apps. These are often fundamental to settings screens, allowing your users to toggle and select the different settings options provided by your application.

Checkbox Preference

In some cases we’ll want to display a preference that allows our user to check and uncheck a preference item, for this we’ll make use of the CheckBoxPreference item:

As you can see from above, there are no extra attributes when compared with our original Preference item, the difference here is that the preference displays a checkbox at the start of the layout. The value fetched for this key will then be returned to us as an enabled or disabled state.

If we are creating the checkbox programatically, then we achieve this by instantiating a new instance of the CheckBoxPreference class:

Switch Preference

Similar to the CheckBox we have the SwitchPreferenceCompat item. Again, no extra attributes are required to configure the display of a switch setting item. And similar to the CheckBox item, the value fetched for this key will then be returned to us as an enabled or disabled state.

If we are creating the switch programatically, then we achieve this by instantiating a new instance of the SwitchPreferenceCompat class:

We also have access to what is known as a DropDownPreference — this preference widget allows us to display a dropdown of selectable items for user selection.

You can see from the above how we require a few extra attributes when it comes to this preference widget:

  • entries: These are the items that you wish to display
  • useSimpleSummaryProvider — Used to determine whether the summary of the preference should show the currently save item
  • entryValues: These are the values which are to be used for the selectable entries.

In some cases it is likely that you want to provide the same set of values for both the entries and the entryValues. However, having these seperate attributes offer you the flexibility for when you need your value set to be different from the values displayed within the drop down itself. For example, the displayed entry of “Entry 1” may actually have the value of “entry_1’. This would not be visible to the user, but is more for use as an internal value.

If we are creating our Preferences programatically, then we can do so by instantiating a new instance of the DropDownPreference class:

Seekbar Preference

The next widget preference we have is the SeekBarPreference, this allows our user to configure a setting which takes on a seekable format, such as volume.

For the seekbar we have a couple of other attributes that we can set other than the usual key and title.

  • max: This represents the maximum value that can be selected using the seekbar
  • defaultValue: This represents the default value to be displayed on the seekbar when it is not / before it is set

Dialog preference items

The preference API provides us with settings items that display a dialog for the user to input some data for the preference item. There are three type of DialogPreference classes that we have available for use — this is the EditTextPreference, ListPreference and MultiSelectListPreference classes:

Each DialogPreference class comes with a collection of attributes which can be used to customise the content which is to be displayed for the given dialog.

  • dialogTitle — The title to be displayed for the dialog
  • dialogMessage — The message to be used within the body of the dialog
  • dialogIcon — The icon to be displayed within the dialog
  • dialogLayoutResource — A custom layout to be used for the dialog
  • positiveButtonText — The string resource to be used for the positive button text
  • negativeButtonText — The string resource to be used for the negative button text

EditText Preference

The first one of these is the EditTextPreference item — this allows our user to input some text to be saved as the value for the preference item.

Other than the common attributes for a dialog preference item, there is a single other attribute available for customising the preference item:

  • useSimpleSummaryProvider — Used to determine whether the summary of the preference should show the currently save item

When this preference item is selected, a dialog will be shown to our user to input the value which is to be saved as the preference value. Whilst all of the DialogPreference attributes do not need to be set, provided values for these allows you to customise the look and feel of the dialog.

If we are creating our preference items programatically, then we can create an EditTextPreference item like so:

Once we have our EditTextPreference defined in our class we can also set a binding listener on it, using the setOnBindEditTextListener method. This allows us to listen for when the dialog for the edit text preference is displayed to the user (from clicking the preference item).

List Preference

Next we have the ListPreference item — this displays a predefined list of items to our user which allows them to select a single item to be assigned as the preference value.

For the list preference item there are a couple of attributes which can be used to configure the list:

  • entries — These are the items that you wish to display
  • useSimpleSummaryProvider — Used to determine whether the summary of the preference should show the currently saved item
  • entryValues — These are the values which are to be used for the selectable entries.

If we are creating our preference items programatically, then we can create an ListPreference item like so:

Finally, the MultiSelectListPreference item works in a similar way to the ListPreference item. The difference is that with this, multiple list values can be selected by the user

  • dialogTitle — The title to be displayed on the dialog
  • entries: These are the items that you wish to display
  • summary: The text summary to be displayed with the setting
  • entryValues: These are the values which are to be used for the selectable entries.
Читайте также:  Android studio напоминание по времени

You’ll notice here that the MultiSelectListPreference does not have useSimpleSummaryProvider option. Instead, you must make use of the summary attribute to provide a summary to be displayed with the setting.

The MultiSelectListPreference can also be created programmatically like so:

Category Preferences

It’s more than likely we’re going to have groups of preferences — as in, preferences items that can be categorised into different groups. In these cases it can be helpful to actually display these in their individual groups to break things up for our users — thankfully, the Preference API provides us with what is known as a PreferenceCategory which allows us to achieve this.

For the PreferenceCategory we only need to define a title, which will be displayed a the top of our categorised settings. Once we have defined this PreferenceCategory within our preferences XML file we just need to play the corresponding Preference items within it.

The PreferenceCategory can also be created programmatically like so:

Expandable Preferences

In some situations there may be a collection of preference items displayed for some part of the settings in our app, and in these cases we may want to allow our user to show and hide this collection. For this, we can make use of the PreferenceCategory item, defining the initialExpandedChildrenCount attribute. When this attribute is defined the category will collapse the remaining items after the initial count that we provided. If there are a lot of settings within a category then this can be used to prevent the user from being overwhelmed with the number of settings that are on display

Because we made use of the initialExpandedChildrenCount attribute when declaring our PreferenceCategory, only the first item is displayed in its expanded state. The remaining items fall into the collapsed state, meaning that the last item must be selected to display these:

At this point, all of our preference items become expanded and visible to the user. This preference configuration is useful where you may have a collection of preferences that are not primary settings for your application — in this case it may make sense to collapse them to avoid bloating the screen and overwhelming the user.

If we are creating the PreferenceCategory programmatically then we can still set the initial expanded count attribute:

Displaying our preferences

In order to display our preferences on the screen to our user, we’re going to need to create a new instance of the PreferenceFragmentCompat class. If we’re going to create our preferences from an xml file then this is going to be a pretty barebones class.

Within this class you’ll notice we override an onCreatePreferences method — this is what is used to configure our preferences screen. Within this, we make use of the setPreferencesFromResource method to assign an xml file which will be used to configure our preferences. Here, our defined xml file will be taken and its contents will be used to build the preferences which are displayed on-screen to the user.

In this fragment, you may also wish to configure your settings programmatically instead of via an xml file. In the previous sections we outlined how you can create settings items programmatically, so let’s take a quick look at how we can apply these within our settings fragment. We begin by making use of the PreferenceManager reference to create an instance of a Preference Screen. When creating via xml all of this configuration is handled for us, in the case of programmatic preference configuration we are required to set these things up ourselves.

Here we do this using the createPreferenceScreen() method on our Preference Manager instance — this returns us an instance of the Preference Screen that we will use to display our settings. Before we can show this to our users though, we need to add our settings items to it. The screen has a method, addPreference(), which allows us to add each of our settings items to the screen. Here we need to call this method for any setting item which we wish to add — so for example we created this in a previous section:

Here, we’ll call addPreference, passing in our notificationCategory instance to add it to our preference screen:

Now that we would have done that for each of our preference items, we can finish off by setting the preferenceScreen property of our Settings Fragment to instance of the Preference Screen that we previously created

At this point, we’ve either added all of our settings items programmatically, or have configured our preferences screen using an xml resource file. So now that we have our settings fragment, we need to actually display it to the user. For this, we’re going to create an activity to house our fragment and set our fragment container to display our settings fragment instance.

Reading preference values

When it comes to reading preferences values, we can make use of the PreferenceManagerclass to retrieve the default shared preferences for our application. From here we can access the preferences value by making use of the key that we assigned it during the definition of our settings.

Listening for preference change events

We can use the OnPreferenceChangeListener to receive a callback when a preference value is being set by the user and is about to be persisted. Within this callback we are required to return a boolean value that states whether or not the preference value should be saved.

Before we can listen for these events though we need to set the listener on the desired Preference item:

We can set a collection of other listeners using the Preference library, read more about them over in the documentation.

In this article we’ve learnt about the different components contained within the Preferences API, along with how we can make use of them when creating Preference screens of our own. Whilst still in alpha, the Preference API aims to make the development process far more streamlined when it comes to settings screens within our applications. Once the Preference API is in a stable position, using it in our applications for these kind of screens seems like the obvious decision to make.

Have you already played with the Preference API, or is it something that you think your application and team will develop from? Please feel free to respond with any thoughts and/or questions

Источник

Оцените статью