根据变量更改progressbar的颜色

czfnxgou  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(325)

我正在用一些progressbar做一个android应用程序。progressbar背景必须始终为白色,而进度颜色必须根据变量进行更改,例如:
如果i<=50:颜色必须为绿色
如果i>50:颜色必须是红色
这是progressbar样式的xml文件:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape
            android:shape="ring"
            android:thicknessRatio="16"
            android:useLevel="false">
            <solid android:color="#FFFF"/>
        </shape>
    </item>
    <item android:id="@android:id/progress">
        <shape
            android:shape="ring"
            android:thicknessRatio="16"
            android:useLevel="true">
            <solid android:color="@color/white" />
        </shape>
    </item>
</layer-list>

进度颜色设置为白色作为背景。我怎样才能改变它?

nzkunb0c

nzkunb0c1#

用xml设置进度条:

<ProgressBar
    android:id="@+id/progressBar1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:indeterminateDrawable="@drawable/nameofyourcustomprogressbar"

访问微调器时,可以设置“进度颜色”属性:

ProgressBar spinner = (ProgressBar) findViewById(R.id.progressBar1);
spinner.getIndeterminateDrawable().setColorFilter(Color.parseColor("#bb86fc"), PorterDuff.Mode.MULTIPLY);

bb86fc是十六进制字符串格式的颜色。

如果您在values/colors.xml中列出了一种颜色,并且希望以这种方式访问颜色:

<resources>
    <color name="purple_200">#FFBB86FC</color>
</resources>

从values/colors.xml访问所需的颜色:

Color.parseColor(getString(R.color.purple_200));

如果得到错误下划线-“expected resource of type string”,只需添加注解

@SuppressLint("ResourceType")

相关问题