Home How to create SeekBarDialogPreference

postheadericon How to create a SeekBarDialogPreference

The standard set of preferences does not provide a SeekBar preference. This article describes how you can implement a SeekBar preference. We do this by making use of a DialogPreference with a custom layout. The layout is done with xml and we also add some custom xml attributes for more control. A sample application is provided to show the working.

We start with creating a SeekBarDialogPreference subclass. Extend it from DialogPreference and implement the SeekBar.OnSeekBarChangeListener interface. For our custom xml attributes we create the /res/values/attrs.xml file. The content looks like this:

<?xml version="1.0" encoding="utf-8"?>
<declare-styleable name="SeekBarDialogPreference">
<attr name="maximumValue" format="integer"></attr>
<attr name="minimumValue" format="integer"></attr>
<attr name="stepSize" format="integer"></attr>
<attr name="units" format="string"></attr>

We have four custom attributes defined here:
- maximumValue int used to provide the maximum value for the seekbar.
- minimumValue int used to provide a minimum value (other than zero) for the seekbar.
- stepSize int used to provide a step size similar to the keyProgressIncrement.
- units string used to provide the units of your seekbar. Displayed after the current value.

Within the /res/xml folder we create a settings.xml file where we define our settings. In this sample just our SeekBarDialogPreference. See listing below.



We define our own schema (cmwmobile) just below where the android schema is defined. Our custom xml attribute is available, now. The next step is to define the layout for the SeekBarDialogPreference. The layout contains a TextView for showing the current value and a SeekBar. The layout file can be found within the /res/layout folder and the file is named: seekbardialogpreference_layout.xml.

We override the onCreateDialogView method to inflate the layout, retrieve the persistent value and initialize the widgets. The onProgressChanged method is also overridden to act on value changes. In our case we round the value to the closest integer value taken the step size into account.

Finally, we override the onClick method of the DialogPreference to persist our new seekbar value. We only act on the positive button and if the value must be stored. And that's it. Have fun and don't forget to like, plus or retweet if you like this blog.

The SeekBarDialogPreference is used within the following apps:
Bubbles·Live Wallpaper
Hearts Live Wallpaper
Lissajous Live Wallpaper
Lissajous Live Wallpaper
PCB·Live Wallpaper
Rose Petals·Live Wallpaper
Spyro·Live Wallpaper
Stars·Live Wallpaper