在 android 中更改进度条背景的颜色

Change color of progress bar background in android

我有一个进度条,它的外观在 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>
            <corners  android:radius="@dimen/round_corners_elements" />
            <solid android:color="@color/blue_50" />

            <stroke android:width="1px" android:color="@color/light_gray" />
        </shape>
    </item>

    <item android:id="@android:id/progress">
        <clip android:clipOrientation="horizontal" android:gravity="left">
            <shape>
                <corners
                    android:radius="@dimen/round_corners_elements"
                   />
                <solid android:color="@color/signaling_color" />
                <stroke android:width="1px" android:color="@color/light_gray" />
            </shape>
        </clip>
    </item>

</layer-list>

但是由于我需要动态地将背景颜色 (blue50) 更改为任何其他颜色,所以我失败了。任何人都知道我如何以编程方式更改它?进度可以保持原样。特别之处在于,进度条是圆角的,这是必须的。我尝试了几种方法,但 none 对我有用。

setBackgroundTintList didn't worked as is only available >API21

int[][] states = new int[][] { new int[] { android.R.attr.background }, new int[] { -android.R.attr.process } };
int[] colors = new int[] { Color.parseColor("#000000"), Color.BLACK };
ColorStateList myList = new ColorStateList(states, colors);
progressBar.setBackgroundTintList(myList);
progressBar.setBackgroundTintMode(PorterDuff.Mode.SRC_OVER);

setBackgroundColor Also had no effect:

 progressBar.setBackgroundColor(ContextCompat.getColor(this, R.color.white));

有人知道吗?

您必须获得 ProgressBar 使用的 LayerDrawable,然后

如果我没记错的话,<shape> 标签会导致 GradientDrawable being created at runtime by the system, and that conveniently has methods like setColor()

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        progressBar.setProgressBackgroundTintList(ColorStateList.valueOf(tint));
    } else {
        LayerDrawable drawable = (LayerDrawable) progressBar.getProgressDrawable();
        Drawable background = new ColorDrawable(tint);
        drawable.setDrawableByLayerId(android.R.id.background, background);
        progressBar.setProgressDrawable(drawable);
    }