Android: Creating custom preference

The Android Developer page only shows how to make a DialogFragment. It’s still possible to customise the appearance of a Preference item though. In your XML you have to declare the root element as android:id="@android:id/widget_frame, and then declare TextView as android:title and android:summary. You can then declare other elements you want to appear in the layout. Here’s an example showing a SeekBar which you could easily adapt to a multi-checkbox colour chooser.

seekbar_preference.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/widget_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@android:id/title"
        style="@android:style/TextAppearance.DeviceDefault.SearchResult.Title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Title" />

    <TextView
        android:id="@android:id/summary"
        style="@android:style/TextAppearance.DeviceDefault.SearchResult.Subtitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Summary" />

    <SeekBar
        android:id="@+id/seekbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

Then, in a class that derives from Preference, override the onCreateView() method:

SeekbarPreference.java

@Override
protected View onCreateView( ViewGroup parent )
{
  LayoutInflater li = (LayoutInflater)getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
  return li.inflate( R.layout.seekbar_preference, parent, false);
}

Then in the preferences.xml file use the preference:

preferences.xml

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

    <com.example.SeekbarPreference
        android:key="pref_max_volume"
        android:title="@string/max_volume" />
    <com.example.SeekbarPreference
        android:key="pref_balance"
        android:title="@string/balance" />

</PreferenceScreen>

This gives a preference that looks as follows:

Seekbar preference item

You can easily adapt this method to show multiple checkboxes on a row as was in the original question.

Leave a Comment