为 ProgressBar drawable 设置不同的颜色但相同 XML drawable

Set different color for ProgressBar drawable but same XML drawable

我正在关注 xml file.I 想用一些背景颜色制作进度条的形状。 但是我的每个 progressBar 都会包含不同的背景颜色。但我只想在一个包含形状和不同颜色的 xml 文件中执行此操作,以便我可以减少可绘制文件中的 xml 个文件。

Custom_horizontal_bar:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background">
        <shape>
            <!--<corners android:radius="25dip" />-->
            <gradient android:startColor="#ffffff" android:centerColor="#ffffff"
                android:centerY="0.75" android:endColor="#ffffff" android:angle="90" />
            <stroke android:width="1dp" android:color="#6B8E23" />
        </shape>
    </item>
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <!--<corners android:radius="25dip" />-->
                <gradient android:startColor="#4d94ff" android:endColor="#4d94ff"
                    android:angle="90" />
                <stroke android:width="1dp" android:color="#6B8E23" />
            </shape>
        </clip>
    </item>
</layer-list>

进度条:

<ProgressBar
              android:id="@+id/myProgress2"

                style="?android:attr/progressBarStyleHorizontal"
                android:layout_width="300dp"
                android:layout_height="30dp"
                android:layout_centerHorizontal="true"

                android:max="100"
                android:progress="60"
                android:progressDrawable="@drawable/custom_horizontal_bar"
                android:secondaryProgress="0" />

欢迎提出建议。

试试这个方法:

1.

LayerDrawable layerDrawable = (LayerDrawable) getResources()
    .getDrawable(R.drawable.Custom_horizontal_bar);
GradientDrawable gradientDrawable = (GradientDrawable) layerDrawable
    .findDrawableByLayerId(R.id.progress);
gradientDrawable.setColor(...);

ProgressBar myProgress2 = (ProgressBar)findViewById(R.id.myProgress2);
myProgress2.setProgressDrawable(gradientDrawable);

2.

ProgressBar myProgress2 = (ProgressBar)findViewById(R.id.myProgress2);

Drawable bgDrawable = myProgress2.getProgressDrawable();
bgDrawable.setColorFilter(Color.BLUE, android.graphics.PorterDuff.Mode.MULTIPLY);
myProgress2.setProgressDrawable(bgDrawable);