Wednesday, November 11, 2009

Slider Bar - The Solution

My quest for a Horizontal Slider Bar has payed off, though it's not a perfect solution. Google has given us something that gets us half-way there - the SeekBar. Really, the SeekBar is for keeping track of progress in a video or music file. It will show you where you are in your file and allow you to jump around by dragging the progress bar. Luckily, it's easy enough to customize to be a pretty decent horizontal slider.

You can create a SeekBar in your main.xml file just like any other component - a simple will get you started. By default, the SeekBar colors everything to the left of the progress bar a very bright orange color. Since, for my purposes, I am not concerned about highlighting the "past", I found a way to make the whole bar a single color. I did this by setting the progressDrawable property to #00000000 (translucent) and then setting the background property to another color that I defined in another XML file. My SeekBar element ended up looking like this -
android:id="@+id/mySeekBar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:progressDrawable="@color/clear_translucent"
android:background="@color/dark_blue_seek_bar"
android:progress="40"/>

The progress property in the SeekBar specifies what the initial value will be.

Next, I wanted to be able to take the present location of the SeekBar and turn it into some kind of meaningful information. To do this, I created an OnSeekBarChangeListener. This class has three methods you need to override - onProgressChanged, onStartTrackingTouch, and onStopTrackingTouch. onProgressChange is where the magic happens. The 'progress' parameter in this method represents the location on the SeekBar with 0 being the far left side and 100 being the far right. I wanted the use my SeekBar to find a number between 0 and 20 and assign it to another text box, so I implemented onProgressChange like this -

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
seekbarConvertedValue.setText(String.valueOf(Math.round(progress / 5)));
}

With this in place, as I move the progress indicator left and right on the SeekBar, I see my textbox update to reflect the current position.

2 comments:

  1. Thanks, Kent, helped me in my app. I guess Google probably intended SeekBar to also serve as a slider, but they should have included an example such as yours in the SeekBar documentation and had an entry in the table of contents/index to point "slider" to SeekBar.

    ReplyDelete
  2. Thank you Kent! Very helpful!

    ReplyDelete