How to set Android SeekBar progress drawable programmatically

Milos Pesic picture Milos Pesic · May 10, 2012 · Viewed 31k times · Source

I have a problem with programmatically setting the progress drawable of a SeekBar. When I set it in the .xml file everything is working fine.

<SeekBar
 android:id="@+id/sb"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 .....
 android:progressDrawable="@drawable/seek_bar"/>

set from .xml

But, I have a problem when I try to set it from code like this:

seekBar.setProgressDrawable(getResources().getDrawable(R.drawable.seek_bar));

Background drawable then takes the whole seek bar, and I'm not able to modify the progress at all later on - the thumb moves but the progress drawable still fills whole seekbar. Also, seekbar looses its rounded corners. It seems that progress drawable is on top of the seekbar.

when set in code

I tried the solution provided on android progressBar does not update progress view/drawable, but it doesn't work for me.

Answer

Milos Pesic picture Milos Pesic · May 16, 2012

I solved the problem by using .xml shape as background for my SeekBar. The complete SeekBar solution that can be used via setProgressDrawable() method should be like this:

//seek_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
    android:id="@android:id/background"
    android:drawable="@drawable/seek_bar_background"/>
<item android:id="@android:id/progress"
    android:drawable="@drawable/seek_bar_progress" />
</layer-list>

//seek_bar_background.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

<gradient
    android:angle="270"
    android:startColor="#8a8c8f"
    android:endColor="#58595b" />

<corners android:radius="5dip" />

</shape>

//seek_bar_progress.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
    android:id="@android:id/background"
    android:drawable="@drawable/seek_bar_background"/>
<item android:id="@android:id/progress">
    <clip android:drawable="@drawable/seek_bar_progress_fill" />
</item>

</layer-list>

//seek_bar_progress_fill.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

<gradient
    android:startColor="#b3d27e"       
    android:endColor="#93c044"
    android:angle="270"
 />
 <corners android:radius="5dip" />  

</shape>

In the code, you can use it like this:

progressBar.setProgressDrawable(getResources().getDrawable(R.drawable.seek_bar));