我一直在寻找您在这里提出的问题,最后,我找到了一个hack,而不是一个解决方案,在该解决方案中,我决定拥有两个具有所需配置的可绘制对象,并将它们分别设置在需要时编码。
想象一下,我想将可绘制的颜色更改为灰色以表明它已被停用。这是正常情况下的drawable:
ic_email_black_18dp.xml
<vector
android:height="18dp"
android:viewportHeight="24.0"
android:viewportWidth="24.0"
android:width="18dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path
android:fillColor="#FF000000"
android:pathData="M20,4L4,4c-1.1,0 -1.99,0.9 -1.99,2L2,18c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2L22,6c0,-1.1 -0.9,-2 -2,-2zM20,8l-8,5 -8,-5L4,6l8,5 8,-5v2z"/>
</vector>
你只是想改变fillColor,所以这里是新的XML文件:ic_email_gray_18dp.xml
<vector
android:height="18dp"
android:viewportHeight="24.0"
android:viewportWidth="24.0"
android:width="18dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path
android:fillColor="#44000000"
android:pathData="M20,4L4,4c-1.1,0 -1.99,0.9 -1.99,2L2,18c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2L22,6c0,-1.1 -0.9,-2 -2,-2zM20,8l-8,5 -8,-5L4,6l8,5 8,-5v2z"/>
</vector>
现在在您的代码中,您可以通过用新的完全替换它来更改可绘制对象的颜色:
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
//Everything else that this button is supposed to do
button.setCompoundDrawablesWithIntrinsicBounds(
R.drawable.ic_email_gray_18dp, //left
0, //top
0, //right
0 //bottom
);
}
});
这个解决方案听起来很有希望,因为复制的文件几乎不占用空间,而且您可以对图标的不同状态进行更多自定义,而无需执行大量不必要的样板代码(当您需要更改的不仅仅是图标中的单色等)。