Click here to Skip to main content
13,350,861 members (54,445 online)
Click here to Skip to main content
Add your own
alternative version


21 bookmarked
Posted 1 Mar 2011

SeekBar Preference

, 1 Mar 2011
Rate this:
Please Sign up or sign in to vote.
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)


About the Author

Software Developer (Senior) Beam Technology
Australia Australia
No Biography provided

You may also be interested in...


Comments and Discussions

QuestionHow to get this persisted value? Pin
Alex Bergsland7-Mar-12 1:56
memberAlex Bergsland7-Mar-12 1:56 
AnswerRe: How to get this persisted value? Pin
Mike1147-Mar-12 2:29
memberMike1147-Mar-12 2:29 
GeneralRe: How to get this persisted value? Pin
Alex Bergsland7-Mar-12 3:07
memberAlex Bergsland7-Mar-12 3:07 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.180111.1 | Last Updated 1 Mar 2011
Article Copyright 2011 by Mike114
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid