ProgressBar 是android中布局中很重要的一个view,现要实现一个竖着的Bar,且能够动态变换进度条的颜色。
1、progressbar 背景图片(xxx.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>
<gradient
android:startColor="#808a87"
android:endColor="#808a87" />
</shape>
</item>
<item
android:id="@android:id/progress">
<shape>
<gradient
android:startColor="#ffffff"
android:endColor="#ffffff" />
</shape>
</item>
</layer-list>
2、progressBar 需竖起来,实现是重写progressBar, 将x,y轴进行互换(来自其他博客)
public class VerticalProgressBar extends ProgressBar {
public VerticalProgressBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public VerticalProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public VerticalProgressBar(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
protected synchronized void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
canvas.rotate(-90);//反转90度,将水平ProgressBar竖起来
canvas.translate(-getHeight(), 0);//将经过旋转后得到的VerticalProgressBar移到正 确的位 置,注意经旋转<span style="white-space: pre;">
super.onDraw(canvas);
}
@Override
protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(heightMeasureSpec, widthMeasureSpec);
setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());//互换宽高值
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(h, w, oldw, oldh);//互换宽高值
}
}
3、实现动态变换颜色,
setProgressImage(); 总是会把替换的图片拉升,铺满整个progressbar。网上很多方法也试过,都没生效,无奈找到一种比较笨的方法,在代码中动态画drawable。代码如下:
**Rect bounds = snr.getProgressDrawable().getBounds();**
Drawable bckgrndDr = new ColorDrawable(getResources().getColor(R.color.pro_ground));
Drawable progressDr20 = new ScaleDrawable(new ColorDrawable(getResources().getColor(R.color.pro_color20)), Gravity.LEFT, 1, -1);
Drawable progressDr40 = new ScaleDrawable(new ColorDrawable(getResources().getColor(R.color.pro_color40)), Gravity.LEFT, 1, -1);
Drawable progressDr60 = new ScaleDrawable(new ColorDrawable(getResources().getColor(R.color.pro_color60)), Gravity.LEFT, 1, -1);
LayerDrawable resultDr = null;
if (snrvalue <= 20) {
resultDr = new LayerDrawable(new Drawable[] { bckgrndDr, progressDr20});
} else if (snrvalue > 20 && snrvalue <= 40) {
resultDr = new LayerDrawable(new Drawable[] { bckgrndDr, progressDr40});
} else {
resultDr = new LayerDrawable(new Drawable[] { bckgrndDr, progressDr60});
}
resultDr.setId(0, android.R.id.background);
resultDr.setId(1, android.R.id.progress);
snr.setProgressDrawable(resultDr);
**snr.getProgressDrawable().setBounds(bounds);**
bounds 值不重新设置的话,drawable的高度会变化,也不知道为什么。
以上方式可以实现动态变化颜色,实验OK。