我在我的Android应用程序中使用水平进度条,我想改变它的进度颜色(默认为黄色)。我如何使用代码(而不是XML)做到这一点?


当前回答

我是如何在水平ProgressBar中做到的:

    LayerDrawable layerDrawable = (LayerDrawable) progressBar.getProgressDrawable();
    Drawable progressDrawable = layerDrawable.findDrawableByLayerId(android.R.id.progress);
    progressDrawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);

其他回答

在新版本的材料设计库中,一个不确定的线性进度指示器似乎可以被制作成多种颜色。

使进度条的动画类型连续可以实现这一点。

在具有此属性的布局中: 应用:indeterminateAnimationType 或者用这个方法编程: setIndeterminateAnimationType ()

更多信息请参考这里。

我是如何在水平ProgressBar中做到的:

    LayerDrawable layerDrawable = (LayerDrawable) progressBar.getProgressDrawable();
    Drawable progressDrawable = layerDrawable.findDrawableByLayerId(android.R.id.progress);
    progressDrawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);

相信我,最简单的解决方法就是把这个粘贴到progressBar中:

android:indeterminateTint="@android:color/white"

我知道我迟到了,但如果你只想改变进度条的颜色,这是最简单的解决方案,在你的主题中,只需添加,

@color - your_color

colorSecondary将改变你整个进程的颜色。

发布了关于PaulieG的答案的补充信息,因为ateiob让我解释一些事情…


我可以说,在ProgressBar代码中存在(或者至少是,当我查看当前版本的Android源代码时)一个错误/问题/优化,忽略了将进度设置为已经存在的值的尝试。

例如,如果progress = 45,而你试图将其设置为45,代码将什么都不做,也不会重绘进度。

调用ProgressBar.setProgressDrawable()后,你的进度条将是空白的(因为你改变了可绘制的部分)。

这意味着你需要设置进度,并重新绘制它。但是如果您只是将进度设置为保留值,它将什么也不做。

您必须先将其设置为0,然后再次设置为“旧”值,然后条将重新绘制。


总结一下:

保留“旧的”进度值 更新可绘制/颜色(使栏空白) 将进度重置为0(否则下一行不执行任何操作) 将进度重置为“旧”值(修复条) 无效


下面是一个方法,我有这样做:

protected void onResume()
{
    super.onResume();
    progBar = (ProgressBar) findViewById(R.id.progress_base);

    int oldProgress = progBar.getProgress();

    // define new drawable/colour
    final float[] roundedCorners = new float[]
        { 5, 5, 5, 5, 5, 5, 5, 5 };
    ShapeDrawable shape = new ShapeDrawable(new RoundRectShape(
        roundedCorners, null, null));
    String MyColor = "#FF00FF";
    shape.getPaint().setColor(Color.parseColor(MyColor));
    ClipDrawable clip = new ClipDrawable(shape, Gravity.LEFT,
        ClipDrawable.HORIZONTAL);
    progBar.setProgressDrawable(clip);

    progBar.setBackgroundDrawable(getResources().getDrawable(
        android.R.drawable.progress_horizontal));

    // work around: setProgress() ignores a change to the same value
    progBar.setProgress(0);
    progBar.setProgress(oldProgress);

    progBar.invalidate();
}

至于HappyEngineer的解决方案,我认为它是一个类似的解决方案,手动设置“进度”偏移量。无论哪种情况,上面的代码都应该适用于您。