2014-01-12 80 views
1

我已经在xml文件中设置了形状,并在按钮上的可绘制右侧使用了xml。感谢这个链接Drawable shape not showing when used in combination with android:drawableBottom attribute.我能够显示形状。我想使用rgb值更改形状的颜色填充。我试过setCompoundDrawablesWithIntrinsicBounds,但我似乎无法将rgb值链接到按钮上的drawableright图像。更改按钮中使用的形状的颜色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; 

回答

3

你应该能够投出DrawableGradientDrawable,并调用其setColor()方法来为它分配一个单独的颜色。请注意,更改颜色将影响从资源加载的所有Drawable实例。如果您也在别处使用它,并且不希望其他实例同时发生更改,则应在Drawable上拨打mutate(),以在更改颜色之前为其提供单独的状态。

所以你的情况,你可以做这样的:

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)); 
+0

你能给我一些代码样本? – Bobby

+0

@Bobby:好的,完成了。 – corsair992

+0

它如何应用于按钮drawableRight?这给我错误\t Fixture1.setCompoundDrawablesWithIntrinsicBounds(0,0,drawable,0); – Bobby