在Android中仅通过代码更改进度条颜色

79

我有一个使用ProgressBar类的进度条。

只需要这样做:

progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);

我需要根据输入值更改那个的颜色,像这样:

int color = "red in RGB value".progressBar.setColor(color)

因为进度条是可定制的,所以我不能使用XML布局

14个回答

1

布局 = activity_main.xml:

<ProgressBar
    android:id="@+id/circle_progress_bar_middle"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    android:max="100"
    android:rotation="-90"
    android:indeterminate="false"
    android:progressDrawable="@drawable/my_drawable_settings2" />

在Java中的Activity/Fragment中:
ProgressBar myProgressBar = (ProgressBar) view.findViewById(R.id.circle_progress_bar_middle);
myProgressBar.setProgressDrawable(getResources().getDrawable(R.my_drawable_settings1));

你的drawable/mipmap文件夹中的my_drawable_settings1.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@android:id/progress">
        <shape
            android:innerRadius="55dp"
            android:shape="ring"
            android:thickness="9dp"
            android:useLevel="true">

            <gradient
                android:startColor="#3594d1"
                android:endColor="@color/white"
                android:type="sweep" />
        </shape>
    </item>
</layer-list>

我的_drawable_settings1和my_drawable_settings2.xml具有不同的颜色。

0

setColorFilter函数的两个参数已经被弃用,而且其他建议使用LightingColorFilter的方法对我也没有起作用。

val progressBar = ProgressBar(context, null, android.R.attr.progressBarStyle).apply {

    val colorFilter = PorterDuffColorFilter(
        ContextCompat.getColor(context, R.color.yourColor),
        PorterDuff.Mode.MULTIPLY
    )

    indeterminateDrawable.colorFilter = colorFilter
}

这将以编程方式为您提供带有您的颜色的圆形进度条


0

试试这个:

progress_wheel.getIndeterminateDrawable().setColorFilter(Color.parseColor(getPreferences().getString(Constant.SECOND_COLOR, Constant.SECONDARY_COLOR)), android.graphics.PorterDuff.Mode.MULTIPLY);

请尝试为您的代码添加一些描述。 - Ruli

-1
尝试这段代码:
   CircularProgressIndicator  circularProgressIndicator = findViewById(R.id.tenant_progress_color);
    circularProgressIndicator.setIndicatorColor(color);
    circularProgressIndicator.setTrackColor(R.color.gray);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接