我在xml文件中设置了一个形状,并在按钮的右侧使用了xml。感谢此链接Drawable shape not showing when used in combination with android:drawableBottom attribute.我能够获得展示的形状。我想使用rgb值更改形状的颜色填充。我尝试过setCompoundDrawablesWithIntrinsicBounds,但我似乎无法将rgb值链接到按钮上的drawableright图像。
这是circle.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"
android:id="@+id/circle2">
<gradient
android:startColor="#FFFF0000"
android:endColor="#80FF00FF"
android:angle="45"/>
<padding android:left="7dp"
android:top="7dp"
android:right="7dp"
android:bottom="7dp" />
<corners android:radius="8dp" />
<size android:width="20dp"
android:height="20dp"/>
</shape>
这是我的按钮
<ToggleButton
android:id="@+id/button6"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:background="@drawable/custom_fixture_buttons"
android:drawableRight="@drawable/circle"
android:textColor="@drawable/white"
android:textOff="F6"
android:textOn="F6"
android:textSize="30sp" />
这是我尝试更改形状颜色。
private void SetColorDot(int index, int i, int j, int k) {
switch (index) {
case 0: {
Resources res = getResources();
final Drawable drawable = res.getDrawable(R.drawable.circle);
drawable.setColorFilter(Color.rgb(i, j, k), Mode.SRC_ATOP);
img.setBackgroundDrawable(drawable);
Fixture1.setCompoundDrawablesWithIntrinsicBounds(0, 0,img, 0);
break;
}
新代码效果很好
private void SetColorDot(int index, int i, int j, int k) {
switch (index) {
case 0: {
Resources res = getResources();
final Drawable drawable = res.getDrawable(R.drawable.circle);
((GradientDrawable) drawable).setColor(Color.rgb(i, j, k));
drawable.mutate();
Fixture1.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
break;
答案 0 :(得分:3)
您应该能够将Drawable
转换为GradientDrawable
,并在其上调用setColor()
方法为其指定一种颜色。请注意,更改颜色将影响从资源加载的所有Drawable
实例。如果您也在其他地方使用它并且不希望其他实例同时更改,那么您应该在mutate()
上调用Drawable
以便在更改之前为其提供单独的状态颜色。
所以在你的情况下,你可以这样做:
Drawable drawable = res.getDrawable(R.drawable.circle);
// Do this only if you are also using the Drawable in another place,
// and don't want it to be changed also.
// drawable.mutate();
((GradientDrawable)drawable).setColor(Color.rgb(i, j, k));