如何在Android 4.x上同时显示多个不同颜色的ProgressBars?

How to show several ProgressBars with different colors on Android 4.x at the same time?

在我的应用程序中,我同时显示了两个不确定的进度条:

我给他们设置了不同的颜色。

((ProgressBar) findViewById(R.id.left_progress)).getIndeterminateDrawable()
        .setColorFilter(new LightingColorFilter(Color.RED, Color.RED));

((ProgressBar) findViewById(R.id.right_progress)).getIndeterminateDrawable()
        .setColorFilter(new LightingColorFilter(Color.BLUE, Color.BLUE));

但是在屏幕上我看到 ProgressBars 只有最后应用的颜色 - 蓝色。

为什么?以及如何给它们应用不同的颜色?

更新:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:layout_marginBottom="50dp"
        android:gravity="center"
        android:orientation="horizontal"
        >

        <ProgressBar
            android:id="@+id/left_progress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="50dp"
            />

        <ProgressBar
            android:id="@+id/right_progress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
    </LinearLayout>
</LinearLayout>

更新二:

仅在 Android API < 5.x.

上转载

将您的代码更改为:

((ProgressBar) findViewById(R.id.left_progress)).getIndeterminateDrawable().mutate()
            .setColorFilter(new LightingColorFilter(Color.RED, Color.RED));

((ProgressBar) findViewById(R.id.right_progress)).getIndeterminateDrawable().mutate()
            .setColorFilter(new LightingColorFilter(Color.BLUE, Color.BLUE));

...这会起作用

在此代码中添加了 .mutate() 函数调用。

这是一篇关于改变可绘制对象的文章 http://android-developers.blogspot.com/2009/05/drawable-mutations.html

用两个词来说,这段代码试图 "modify" 一个不可变且本质上共享的可绘制对象。 我只是引用文章中的一句话:

在变异之前我们有:

The following diagram shows what entities are created when you assign the same image resource as the background of two different views. As you can see, two drawables are created but they both share the same constant state, hence the same bitmap:

变异后:

When you invoke this method on a drawable, the constant state of the drawable is duplicated to allow you to change any property without affecting other drawables. Note that bitmaps are still shared, even after mutating a drawable. The diagram below shows what happens when you invoke mutate() on a drawable: