You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过代码动态修改自定义ProgressBar的颜色?已解决

动态修改自定义水平ProgressBar颜色的问题与解决方案

一、相关实现代码

1. 主布局中的ProgressBar配置(activity_main.xml)

<ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginBottom="8dp"
    android:progressDrawable="@drawable/custom_progress"
    android:background="@drawable/custom_progress_bar"
    android:max="100"
    android:progress="80" />

2. 自定义进度条Drawable文件

custom_progress_bar.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 android:shape="rectangle">
            <corners android:radius="8dp"/>
            <solid android:color="@color/white"/>
        </shape>
    </item>
</layer-list>

custom_progress.xml(进度填充层)

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/progress_solid">
        <clip>
            <shape android:shape="rectangle">
                <corners android:radius="8dp"/>
                <solid android:color="@color/progress"/>
            </shape>
        </clip>
    </item>
</layer-list>

二、最初无效的修改代码(MainActivity.java)

以下代码试图将进度条从默认绿色(@color/progress)改为红色,但运行后未达到预期效果:

LayerDrawable layerDrawable = (LayerDrawable) ContextCompat.getDrawable(this, R.drawable.custom_progress);
ClipDrawable progressSolid = (ClipDrawable) layerDrawable.findDrawableByLayerId(R.id.progress_solid);
GradientDrawable gradientDrawable = new GradientDrawable();
gradientDrawable.setColor(Color.RED);
progressSolid.setDrawable(gradientDrawable);
progressBar.invalidate();

三、可行的解决方案

替换为以下代码后,可成功将进度条改为红色:

LayerDrawable layerDrawable = (LayerDrawable) progressBar.getProgressDrawable();
Drawable progressFill = layerDrawable.getDrawable(1);
progressFill.setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);

内容的提问来源于stack exchange,提问作者sbonelo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 07:16:07