Building an Android Settings Screen (Part 4)

How to Use a Custom Layout for the Preference Fragment

Jakob Ulbrich
2 min readAug 22, 2016

This part of the tutorial was originally published as an answer to a question in third Part of my tutorial series. (You may want to go back to the first Part or the second Part.) It will tell you how you can use a custom layout for the PreferenceFragmentCompat from the v7 preferences support library. Just follow the simple steps below.

First, go to your style.xml file and search for your App’s Theme (The Theme which is used for the Activity where your PreferenceFragment belongs to). It should look like this at the moment:

<style name="AppTheme" parent="Theme.AppCompat">
...
<item name="preferenceTheme">
@style/PreferenceThemeOverlay.v14.Material
</item>
...
</style>

Found it?
Then change it to this:

<style name="AppTheme" parent="Theme.AppCompat">
...
<item name="preferenceTheme">
@style/AppPreferenceTheme
</item>
...
</style>

and add the following two styles:

<!-- Custom Preference Theme -->
<style name="AppPreferenceTheme"
parent="@style/PreferenceThemeOverlay.v14.Material">
<item name="preferenceFragmentCompatStyle">
@style/AppPreferenceFragmentCompatStyle
</item>
</style>
<!-- Custom Style for PreferenceFragmentCompat -->
<style name="AppPreferenceFragmentCompatStyle"
parent="@style/PreferenceFragment.Material">
<item name="android:layout">@layout/pref_screen</item>
</style>

In our custom AppPreferenceTheme (which inherits from the v14 Material Theme) we override the style for PreferenceFragmentCompat.
In AppPreferenceFragmentCompatStyle (which inherits from the default Material one to keep the other predefined attributes) we finally change the layout for it.

In your layout file (in this case pref_screen.xml) you must include a ViewGroup with the id @+id/list_container (support library version 23.4.0) or @android:id/list_container (support library version 24.2.0).

Note that Google changed the needed id from R.id.list_container (in revision 23.4.0) to android.R.id.list_container (in revision 24.0.0). Android Studio says the new id requires API 24, but it also works on older APIs.

It should look like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button in custom layout"/>

<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@android:id/list_container"
/>
</LinearLayout>

Your App should now look similar to this:

I think you can access the Views from your layout in the onCreateView method of the PreferenceFragmentCompat.

You can have a look at the project files on GitHub.

Thanks for reading and happy coding 💻.

--

--