Preferences screen using XML
How is your preference screen going to look? What elements do we need? The first step is designing the screen, and we are going to use XML for that. I will give you useful pieces of code so you can build your own preferences screen according to your needs.
In a common Android screen we can find “LinearLayouts" or “RelativeLayouts" as elements containers. Here, looking at the preferences screen, we will find two kinds of containers:
PreferenceScreen and the PreferenceCategory
The PreferenceScreen tag is the parent container, for every different screen we will have one of these containers. On the other hand, the PreferenceCategory tag is used to create divisions in the screen by category, for example. Here in the following image you can see the divisions I was talking about:
Every gray row is a different category you can define using the PreferenceCategory tag:
<PreferenceCategory android:title="First category">
… put whatever preference element here.
What about the inside elements? Here are some examples:
If you want to add a checkbox in your preference screen, like this one:
The code you need to add to the XML is the following:
android:defaultValue="false" android:summary="This can be true or false"
Here we can see the most useful tags in a preference element:
android:title → Obviously, this text gives the title to the preferences.
android:defaultValue → This is the default value of the current preference, in this case it is false because we are in a true/false value preference.
android:summary → This text gives the user a little more information about the preference.
android:key → Very important tag, this is the identifier value of the current preference. Using this key we will be able to work with the preference within the application in our Android code.
Let's see some more preferences elements:
This is an editable preference, you can store here any text value you want.
android:summary="You can input text here" android:defaultValue="Empty"
android:title="TextToInput" android:key="editTextPref" />
Again, here we find the same tags as above.
The list preference like the following one:
is coded as follows:
android:summary="Array preferences selection" android:key="listPref"
The list is filled with predefined arrays (created in arrays.xml).
A curious preference element, is the “Ring tone selector":
android:summary="Select a ringtone" android:title="RingTones"
This code will allow a user to select a ringtone from the available tones in the phone and then stores it in that preference value.