我们在使用progressbar的时候希望设定一下背景颜色和progress颜色,那我们必然会用到layer-list
第一种方法 在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">
<shape android:shape="rectangle" >
<solid android:color="#eaeaea" />
</shape>
</item>
<item android:id="@android:id/progress">
<clip>
<shape>
<solid android:color="#54a1fd" />
</shape>
</clip>
</item>
</layer-list>
看上面的item ID可以很清晰的看到前景色和背景色,这里需要说明一下前景色progress需要用clip去剪切一下,不然不会出现进度的style
第二种方法 代码中添加layer-list
Drawable[] layers = new Drawable[2];
Drawable background = mContext.getResources().getDrawable(R.drawable.progress_background);
GradientDrawable progress = (GradientDrawable) mContext.getResources().getDrawable(R.drawable.progress_progress);
progress.setColor(mContext.getResources().getColor(R.color.red));
ClipDrawable clip = new ClipDrawable(progress,Gravity.LEFT, ClipDrawable.HORIZONTAL);
layers[0] = background;
layers[1] = clip;
LayerDrawable layer=new LayerDrawable(layers );
layer.setId(0, android.R.id.background);
layer.setId(1, android.R.id.progress);
mBbPlay.setProgressDrawable(layer);
上面两种完全可以满足基本的要求,但是我们产品UI设计中有时候会对progressbar的每个进度颜色都会有不一样的需求
那我们完全获取到前景色,然后动态的根据需求去设置颜色
LayerDrawable layerDrawable = (LayerDrawable)mBbPlay.getProgressDrawable();
Drawable draw = layerDrawable.findDrawableByLayerId(android.R.id.progress);
GradientDrawable progress;
if(draw == null || !(draw instanceof ColorDrawable)){
progress = (GradientDrawable) mContext.getResources().getDrawable(R.drawable.progress_progress);
draw = new ColorDrawable(progress, Gravity.LEFT, ClipDrawable.HORIZONTAL);
layerDrawable.setDrawableByLayerId(android.R.id.progress, draw);
}else{
progress = ((ColorDrawable)draw).progress;
}
progress.setColor(mContext.getResources().getColor(R.color.red));
public class ColorDrawable extends ClipDrawable{
public GradientDrawable progress;
public ColorDrawable(GradientDrawable drawable, int gravity, int orientation) {
super(drawable, gravity, orientation);
progress = drawable;
}
}