[英]How to change the color of an item(ScaleDrawable) of an existing layer-list programatically
我有一个用于自定义ProgressBar的现有图层列表,如下所示:
style_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"
android:drawable="#F6F3F1" />
<item android:id="@android:id/secondaryProgress">
<scale
android:drawable="#DE0012"
android:scaleWidth="100%" />
</item>
<item android:id="@android:id/progress">
<scale
android:drawable="#DE0012"
android:scaleWidth="100%" />
</item>
</layer-list>
该层列表用于覆盖ProgressBar的progressDrawable属性,其工作方式类似于超级按钮。
现在,我想使用相同的主干,但是我想以编程方式更改第二和第三项的颜色,因为在许多情况下进度颜色应该会发生变化,并且我不愿意创建大量的xml文件甚至都不是一个好主意。
我设法阅读了上面的文件,并阅读了第二和第三项,但找不到改变这些颜色的正确解决方案。2。除颜色问题外,其他所有操作均按预期进行。
LayerDrawable layers = (LayerDrawable) getResources().getDrawable(R.drawable.style_progress_bar);
int color = getResources().getColor(colorId); // This is the ID of the new color. I use it elsewhere so this should be 100% good
layers.getDrawable(1).setColorFilter(color, PorterDuff.Mode.MULTIPLY);
layers.getDrawable(2).setColorFilter(color, PorterDuff.Mode.MULTIPLY);
// I even called invalidate(); after all this. Nothing changed
我觉得我真的要结束这个了,但是我被卡住了。
有任何想法吗? 谢谢!
好吧,我真的在这里领先了,对不起。
深入研究后,我意识到我可以将所需的2个可绘制对象读取为ScaleDrawable对象,因为这是在xml文件中将它们作为比例设置的方式。
这些比例尺项中的每一个都有其自己的可绘制对象集:
<scale
android:drawable="#DE0012"
android:scaleWidth="100%" />
所以我意识到,那些也可以以某种方式阅读。 是的,它们可以读取为ColorDrawable对象。 至此,我有了2个ColorDrawable对象,我可以简单地为其设置颜色。 这是我完成所有工作的最终代码:
private Drawable createDrawable(int colorId) {
LayerDrawable layers = (LayerDrawable) getResources().getDrawable(R.drawable. style_progress_bar);
int color = getResources().getColor(colorId);
try {
ScaleDrawable first = (ScaleDrawable) layers.getDrawable(1);
ScaleDrawable second = (ScaleDrawable) layers.getDrawable(2);
ColorDrawable secondaryColor = (ColorDrawable) first.getDrawable();
secondaryColor.setColor(color);
ColorDrawable primaryColor = (ColorDrawable) second.getDrawable();
primaryColor.setColor(color);
} catch (ClassCastException e) {
e.printStackTrace();
}
return layers;
}
之后,我可以简单地调用上述方法,并动态更改我的颜色。
progressBar.setProgressDrawable(createDrawable(colorId));
谢谢,对此表示歉意,但是我想我要解决这个问题,以防其他人在需要使用ScaleDrawable时遇到这种特殊情况。
请注意,在xml layer-list的项目中使用除比例尺之外的其他方法,将使progressView完全着色,并且您将无法获得所需的结果,例如使用不同的背景色和实际进度的另一种颜色。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.