1

我想要一个有两种颜色的进度条。有时我想增加红色进度和绿色一些时间。简而言之,我想将进度条一分为二。如果我想以红色增加进度,一个绿色部分和另一个红色部分将以红色增加,与绿色相同。请注意,进度从左开始。我怎样才能做到这一点。我知道我应该使用次要进度但是如何?这是我的代码和我正在尝试做的事情。

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 的东西。

4

1 回答 1

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

该代码只是如何完成它的示例。可以进行一些改进,例如,您可以将视图的宽度和高度值存储在局部变量中以避免一直调用getWidthgetHeight但您只能在特定位置执行此操作,例如在活动onWindowFocusChanged回调中,否则 getWidth 和 getHeight将返回 0。空条也可以用适当的值初始化一次,以避免每次都设置。

于 2012-09-07T13:40:57.780 回答