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


当前回答

在Xml中添加ProgressBar

适用于SDK 21及以上版本

android:indeterminateTint="@color/red"

其他回答

对于水平的ProgressBar,你也可以使用ColorFilter,就像这样:

progressBar.getProgressDrawable().setColorFilter(
    Color.RED, android.graphics.PorterDuff.Mode.SRC_IN);

注意:这将修改应用程序中所有进度条的外观。要只修改一个特定的进度条,请执行以下操作:

Drawable progressDrawable = progressBar.getProgressDrawable().mutate();
progressDrawable.setColorFilter(Color.RED, android.graphics.PorterDuff.Mode.SRC_IN);
progressBar.setProgressDrawable(progressDrawable);

如果progressBar是不确定的,则使用getIndeterminateDrawable()而不是getProgressDrawable()。

因为棒棒糖(API 21),你可以设置一个进度色调:

progressBar.setProgressTintList(ColorStateList.valueOf(Color.RED));

很抱歉,这不是答案,但是是什么驱使需求从代码中设置它呢? 如果定义正确。setprogressdrawable应该工作

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@android:id/background">
    <shape>
        <corners android:radius="5dip" />
        <gradient
                android:startColor="#ff9d9e9d"
                android:centerColor="#ff5a5d5a"
                android:centerY="0.75"
                android:endColor="#ff747674"
                android:angle="270"
        />
    </shape>
</item>

<item android:id="@android:id/secondaryProgress">
    <clip>
        <shape>
            <corners android:radius="5dip" />
            <gradient
                    android:startColor="#80ffd300"
                    android:centerColor="#80ffb600"
                    android:centerY="0.75"
                    android:endColor="#a0ffcb00"
                    android:angle="270"
            />
        </shape>
    </clip>
</item>

<item android:id="@android:id/progress">
    <clip>
        <shape>
            <corners
                android:radius="5dip" />
            <gradient
                android:startColor="@color/progress_start"
                android:endColor="@color/progress_end"
                android:angle="270" 
            />
        </shape>
    </clip>
</item>

</layer-list>

如果有人想通过编程改变颜色:

progressBar.progressTintList = ColorStateList.valueOf(Color.RED)
android:progressTint="#ffffff" 

在修改默认进度条的外观时遇到了同样的问题。这里有一些更多的信息,希望能帮助到人们:)

The name of the xml file must only contain characters: a-z0-9_. (ie. no capitals!) To reference your "drawable" it is R.drawable.filename To override the default look, you use myProgressBar.setProgressDrawable(...), however you need can't just refer to your custom layout as R.drawable.filename, you need to retrieve it as a Drawable:Resources res = getResources(); myProgressBar.setProgressDrawable(res.getDrawable(R.drawable.filename); You need to set style before setting progress/secondary progress/max (setting it afterwards for me resulted in an 'empty' progress bar)