如何以编程方式设置Android SeekBar进度可绘制

问题描述:

我在编程上设置SeekBar的可绘制进度时遇到问题. 当我在.xml文件中进行设置时,一切正常.

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"/>

设置

但是,当我尝试从这样的代码进行设置时,我遇到了一个问题:

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

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

然后,背景可绘制对象占据了整个搜索栏,后来我根本无法修改进度-拇指移动了,但是进度可绘制对象仍然充满了整个搜索栏.此外,seekbar会松开其圆角.似乎可绘制进度位于搜索栏的顶部.

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.

我尝试了提供的解决方案android progressBar不会更新进度视图/drawable ,但这对我不起作用.

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

我通过使用.xml shape作为我的SeekBar的背景解决了这个问题. 可以通过setProgressDrawable()方法使用的完整SeekBar解决方案应如下所示:

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));