我想要一个有两种颜色的进度条。有时我想增加红色进度和一些绿色的时间。简单来说,我想将进度条分成两部分。一个绿色部分和其他红色,如果我想增加红色的进度,它将增加红色和绿色相同。请注意,进度从左开始。我怎样才能做到这一点。我知道我应该使用次要进展但是如何?这是我的代码和我想要做的。
final float[] roundedCorners = new float[] { 5, 5, 5, 5, 5, 5, 5, 5 };
ShapeDrawable pgDrawable = new ShapeDrawable(new RoundRectShape(
roundedCorners, null, null));
if (answer == true) {
pgDrawable.getPaint().setColor(Color.parseColor(greenColor));
Log.i("green", ": should work");
} else if (answer == false) {
pgDrawable.getPaint().setColor(Color.parseColor(redColor));
Log.i("red", ": should work");
}
ClipDrawable progress = new ClipDrawable(pgDrawable, Gravity.LEFT,
ClipDrawable.HORIZONTAL);
progressBarTotal.setProgressDrawable(progress);
progressBarTotal.setBackgroundDrawable(getResources().getDrawable(
android.R.drawable.progress_horizontal));
if (TotalPercent >= 102) {
Toast.makeText(ProcessGame.this, "Full", Toast.LENGTH_LONG).show();
} else {
progressBarTotal.setProgress(TotalPercent);
TotalPercent = (TotalPercent + 1);
}
如果可以在java中完成,我不想搞乱xml的东西。
答案 0 :(得分:0)
您可以创建自己的视图。
public class CustomProgressBar extends View{
public CustomProgressBar(Context context, AttributeSet attribs){
super(context, attribs);
float xRadius = 5f, yRadius = = 5f;
Paint emptyPaint = new Paint();
emptyPaint.setColor(Color.WHITE);
Paint greenPaint = new Paint();
greenPaint.setColor(Color.GREEN);
Paint redPaint = new Paint();
redPaint.setColor(Color.RED);
Rectf emptyBar = new Rectf(0,0,0,0);
Rectf greenBar = new Rectf(0,0,0,0);
Rectf redBar = new Rectf(0,0,0,0);
}
public void setProgress(float greenProgress, float redProgress){
//progress should be between 0f and 1f
//but you can change it, just change how the width is calculated
emptyBar.set(0,0,getWidth(), getHeight());
greenBar.set(0,0,getWidth() * greenProgress, getHeight());
redBar.set(0,0,getWidth() * redProgress, getHeight());
//force the view to draw again
invalidate();
}
@Override
protected void onDraw(Canvas canvas){
canvas.drawRoundRect(emptyBar, xRadius,yRadius, emptyPaint);
canvas.drawRoundRect(greenBar, xRadius,yRadius, greenPaint);
canvas.drawRoundRect(redBar, xRadius,yRadius, redPaint);
}
}
在xml中,视图看起来像
<com.mydomain.widgets.CustomProgressBar
android:layout_width="fill_parent"
android:layout_height="10dip"
/>
代码只是如何完成它的一个例子。可以进行一些改进,例如,您可以将视图的宽度和高度值存储在局部变量中,以避免始终调用getWidth
和getHeight
,但您只能在特定位置执行此操作,比如你的活动onWindowFocusChanged
回调,否则getWidth和getHeight将返回0.空栏也可以使用适当的值初始化一次,以避免每次都设置。