遗憾的是,您不能将参数传递给 XML Drawables。
如果您没有太多不同的值,则可以使用 a<level-list>
并提供不同版本的形状。
然后,您将更改与您的可绘制对象关联的级别以使用Drawable.setLevel(int)
.
my_drawable.xml
<level-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:maxLevel="0">
<shape android:shape="oval">
<solid android:color="@color/red"/>
<stroke android:width="1sp" android:color="@color/border" />
</shape>
</item>
<item android:maxLevel="1">
<shape android:shape="oval">
<solid android:color="@color/green"/>
<stroke android:width="1sp" android:color="@color/border" />
</shape>
</item>
<item android:maxLevel="2">
<shape android:shape="oval">
<solid android:color="@color/blue"/>
<stroke android:width="1sp" android:color="@color/blue" />
</shape>
</item>
</level-list>
我的活动.java
// myView is a View (or a subclass of View)
// with background set to R.drawable.my_drawable
myView.getBackground().setLevel(0); // Set color to red
myView.getBackground().setLevel(1); // Set color to green
myView.getBackground().setLevel(2); // Set color to blue
// myImageView is an ImageView with its source
// set to R.drawable.my_drawable
myImageView.setImageLevel(0); // Set color to red
myImageView.setImageLevel(1); // Set color to green
myImageView.setImageLevel(2); // Set color to blue