2016-07-24 53 views
1

我在我的約束佈局中有一個如下所示的圖標:icon如何更改可繪製集的顏色爲android:background?

這是我爲這個圖像視圖佈局的xml:

<ImageView 
     android:id="@+id/vTotalPaidAvatar" 
     android:layout_width="40dp" 
     android:layout_height="40dp" 
     android:contentDescription="@null" 
     android:src="@drawable/ic_group_ic_total" 
     tools:src="@drawable/ic_group_ic_total" 
     app:layout_constraintLeft_toLeftOf="@+id/vSettleDebtsLayout" 
     android:layout_marginLeft="16dp" 
     android:layout_marginStart="16dp" 
     app:layout_constraintTop_toTopOf="@+id/vSettleDebtsLayout" 
     android:layout_marginTop="16dp" 
     android:background="@drawable/avatar_circle" /> 

正如你可以看到,圖標只是一個美元符號。我將該灰色圓圈設置爲背景。問題是我需要動態改變背景的顏色。美元符號需要保持白色。 我的問題是,有沒有辦法如何改變只有背景的顏色?

另一種解決方案是將該圓圈用作下一個imageview,然後更改該圖像視圖的顏色。但我認爲有可能是這個問題的一些「澄清溶液。

感謝提示:)

回答

2

嘗試:

yourImage.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN); 

字面上得到背景(不src)從ImageView,涵蓋了與顏色形狀。可拉伸和給定顏色相結合的方式由Porter Duff模式定義 - here您有更多關於它的信息。要做到這一點

+0

你解決了我的問題。謝謝 :) –

0

你嘗試android:background="@color/my_color"並通過代碼imageView.setBackgroundColor(Color.rgb(255, 255, 255));

+0

我需要使用圈子作爲背景,然後我需要更改圓的顏色。這是可繪製的...我不能只使用顏色作爲背景它將填充所有空間專用於我的圖像視圖 - >(它不會有一個圓形狀) –

1

孔U必須設法

android:backgroundTint="your color" 

在imageview的標籤

這將做的工作

+0

是的,但我需要更改代碼中的背景色調,有沒有方法像setBackgroundTintColor –

2

最好的辦法:

public static void colorDrawable(View view, int color) { 
      Drawable wrappedDrawable = DrawableCompat.wrap(view.getBackground()); 
      if (wrappedDrawable != null) { 
       DrawableCompat.setTint(wrappedDrawable.mutate(), color); 
       setBackgroundDrawable(view, wrappedDrawable); 
      } 
     } 

public static void setBackgroundDrawable(View view, Drawable drawable) { 
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { 
     view.setBackgroundDrawable(drawable); 
    } else { 
     view.setBackground(drawable); 
    } 
} 
相關問題