2012-03-23 104 views
9

我有自定義的搜索條,我可以在改變顏色的通過設置新的進展繪製onProgressChanged:更改搜索條的顏色上onProgressChanged

seek.setProgressDrawable(res.getDrawable(R.drawable.seekbar_bg1)); 

但我想搜索條至極具有純色從綠色到紅色取決於進度。 有沒有辦法使用像漸變顏色的東西,所以我不需要創建像這樣的100 drawables?

<?xml version="1.0" encoding="utf-8"?> 
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> 

<item android:id="@android:id/background"> 
    <shape> 
    <solid android:color="@android:color/transparent" /> 
    </shape> 
</item> 

<item android:id="@+id/progressshape"> 
<clip> 
    <shape> 
    <solid android:color="@color/custom_yellow" /> 
    </shape> 
</clip> 
</item> 

</layer-list> 

對於那些有興趣誰在溶液中。我使用下面的代碼:

這種方法來設置顏色:

public void setProgressBarColor(int newColor){ 
    LayerDrawable ld = (LayerDrawable) getProgressDrawable(); 
    ClipDrawable d1 = (ClipDrawable) ld.findDrawableByLayerId(R.id.progressshape); 
    d1.setColorFilter(newColor, PorterDuff.Mode.SRC_IN); 
} 

,並在onProgressChanged:

if(progress <= 50){ 
       seek.setProgressBarColor(Color.rgb(255 - (255/100 * (100 - progress*2)), 255, 0)); 
}else{ 
       seek.setProgressBarColor(Color.rgb(255, 255 - (255/100 * (progress - 50)*2), 0)); 
} 

回答

24

我做這樣的事情用這個方法:

public void setProgressBarColor(ProgressBar progressBar, int newColor){ 
    LayerDrawable ld = (LayerDrawable) progressBar.getProgressDrawable(); 
    ClipDrawable d1 = (ClipDrawable) ld.findDrawableByLayerId(R.id.progressshape); 
    d1.setColorFilter(newColor, PorterDuff.Mode.SRC_IN); 

} 

然後,當你更新進度,你只需要改變所需的顏色。

+0

Thnx,這幫了我很多:) – Luciano 2012-03-23 13:36:55

+0

如何訪問默認使用的R.id.progressshape? – snapfractalpop 2012-04-09 15:30:07

+3

「android.R.id.progress」通過代碼或「@android:id/progress」通過xml(不知道這是不是你要求的) – Alesqui 2012-04-09 16:01:48

4

使用此:

bar.setProgressDrawable(new ColorDrawable(Color.rgb(red, green, blue))); 

將紅,綠色,藍色,進度變化。

+0

thnx試圖幫助,但可繪製的進度需要像上面那樣(一個帶有形狀和剪輯的層列表)你知道我該如何以編程方式創建這個drawable或在運行時編輯剪貼圖形狀顏色嗎? – Luciano 2012-03-23 13:12:00