Click here to Skip to main content
15,606,221 members
Articles / Mobile Apps / Android
Posted 1 Mar 2011

Tagged as


21 bookmarked

SeekBar Preference

Rate me:
Please Sign up or sign in to vote.
4.80/5 (10 votes)
1 Mar 2011CPOL3 min read
How to build preference widget with SeekBar


In this article, I’ll try to show how to create your own preference widget with SeekBar inside.



Android provides a number of handy widgets like CheckBoxPreference, EditTextPreference, ListPreference to build nice preference screens. But if existing widgets somehow don’t fit your requirements, you can easily create your own based on existing.

Often some integer preferences have meaningful limitations like volume or brightness level. In this case, it makes sense to build your own widget to manage such preferences and then reuse this widget across applications.


DialogPreference is the best super class for such widgets. It provides a preference which shows two lines of text in preference list (title and summary) and shows dialog with Ok / Cancel buttons on click.


Let's call it SeekBarPreference. Parameters for this widget can be minimum value, maximum value and current default value. Real current value will be stored in associated shared preferences by given key.

In this case, file /res/xml/preferences.xml can look like this:

	example:maxValue="50" />

Existing tag can be used to setup default current value. But minimum and maximum values need their own tags. For this /res/values/attrs.xml file should be extended with the next declaration:

<?xml version="1.0" encoding="utf-8"?>
    <declare-styleable name="com.mnm.seekbarpreference.SeekBarPreference">
        <attr name="minValue" format="integer" />
        <attr name="maxValue" format="integer" />

Name attribute of <declare-styleable> tag should contain qualified widget class name.

The same name but in more full format ( should be defined in preferences.xml as additional namespace (see above).

The last stage of work with XML is the creation of layout for dialog launching on widget click. It is a really common code and could be omitted without any impact. Just mention that it contains minimum, maximum and current values’ TexViews and SeekBar.

Now, we can continue with SeekBarPreference class implementation.


At first, all mentioned attributes shall be read in widget constructor:

mMinValue = attrs.getAttributeIntValue
mMaxValue = attrs.getAttributeIntValue
mDefaultValue = attrs.getAttributeIntValue

where constants are names of namespaces, attributes and default values for attributes’ values (in case they are omitted in preference declaration):

private static final String PREFERENCE_NS = 
private static final String ANDROID_NS = "";

private static final String ATTR_DEFAULT_VALUE = "defaultValue";
private static final String ATTR_MIN_VALUE = "minValue";
private static final String ATTR_MAX_VALUE = "maxValue";

For dialog setup, onCreateDialogView method should be overridden:

protected View onCreateDialogView() {

    // Get current value from settings
    mCurrentValue = getPersistedInt(mDefaultValue);

    // Inflate layout
    LayoutInflater inflater = 
	(LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.dialog_slider, null);

    // Put minimum and maximum
    ((TextView) view.findViewById(;
    ((TextView) view.findViewById(;

    // Setup SeekBar
    mSeekBar = (SeekBar) view.findViewById(;
    mSeekBar.setMax(mMaxValue - mMinValue);
    mSeekBar.setProgress(mCurrentValue - mMinValue);

    // Put current value
    mValueText = (TextView) view.findViewById(;

    return view;

Current value is gotten by key stated in preferences.xml for a particular widget instance. Also during SeekBar setup should be taken into account that minimum value for it is zero. This is the reason why subtraction is used when minimum value of preference differs from zero. By the way, this code is correct for non-negative numbers only and when maximum value is really greater than minimum one.

After the previous step, the application can be launched and user can drag thumb but text on the current value label wouldn’t change because position change handler should be introduced.

For this purpose, SeekBarPreference should implement OnSeekBarChangeListener interface. In the previous code, exactly this interface was passed via “mSeekBar.setOnSeekBarChangeListener(this);” call to SeekBar. Only one method should be implemented from three possible:

public void onProgressChanged(SeekBar seek, int value, boolean fromTouch) {
    mCurrentValue = value + mMinValue;

And again, addition should be used because SeekBar minimum value is zero.

Next step is to persist changed value. On dialog close, it calls onDialogClosed method that should be overridden:

protected void onDialogClosed(boolean positiveResult) {

    if (!positiveResult) {
    if (shouldPersist()) {


On positive result value is persisted and shouldPersist() check analyzes if it is necessary according to flag android:persistent from preferences.xml.

Last line is needed for a small trick. The point is that by default, summary line of the widget is static and if it should reflect current value, the next code should be added:

public CharSequence getSummary() {
    String summary = super.getSummary().toString();
    int value = getPersistedInt(mDefaultValue);
    return String.format(summary, value);

Here on summary request, the original string is treated like a template to put current value into it. It works perfectly on preferences screen open. But to get the same behavior after preference change via dialog, notifyChanged() should be called.


Implemented widget is suitable for a wide range of preferences and it elegantly extends existing set of preference widgets. Dynamic summary line approach can be used across different preference widgets.



  • 1st March, 2011: Initial post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer (Senior) Beam HQ
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

Questionadd an custom seekbar on notification bar Pin
jay_20084-Dec-15 19:52
jay_20084-Dec-15 19:52 
GeneralMy vote of 5 Pin
jay_20084-Dec-15 19:49
jay_20084-Dec-15 19:49 
GeneralMy vote of 5 Pin
Mingliang Zhu5-Jun-14 19:59
Mingliang Zhu5-Jun-14 19:59 
QuestionG R E A T!! Pin
Luca Crisi, MCP29-Nov-13 4:44
Luca Crisi, MCP29-Nov-13 4:44 
QuestionNICE!! Pin
Muhammad Mhajna19-Jul-13 10:37
Muhammad Mhajna19-Jul-13 10:37 
QuestionImproved preference summary trick. Pin
Steve Waring26-Mar-13 9:15
Steve Waring26-Mar-13 9:15 
QuestionGreat example, but... Pin
Steve Waring25-Mar-13 6:26
Steve Waring25-Mar-13 6:26 
GeneralMy vote of 5 Pin
NetDave9-Jan-13 17:19
NetDave9-Jan-13 17:19 
Bugcommit a bug:about OnPreferenceChangeListener Pin
WildDeer1-Jun-12 17:20
WildDeer1-Jun-12 17:20 
QuestionHow to get this persisted value? Pin
Alex Bergsland7-Mar-12 0:56
Alex Bergsland7-Mar-12 0:56 
AnswerRe: How to get this persisted value? Pin
Mike1147-Mar-12 1:29
Mike1147-Mar-12 1:29 
GeneralRe: How to get this persisted value? Pin
Alex Bergsland7-Mar-12 2:07
Alex Bergsland7-Mar-12 2:07 
Questionthanks! but what happans when you trying to add multiple custom preferences? Pin
Roy Barina10-Dec-11 11:01
Roy Barina10-Dec-11 11:01 
AnswerRe: thanks! but what happans when you trying to add multiple custom preferences? Pin
Mike11412-Dec-11 18:25
Mike11412-Dec-11 18:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.