2014-01-12 79 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