2016-06-27 59 views
0

我有一個ImageButton,它有一個橢圓形的可繪製背景資源。更改Android上ImageView的BackgroundTint

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="oval"> 
    <solid 
     android:angle="270" 
     android:color="#FFFF0000" /> 

</shape> 

這裏是XML的ImageButton的:

<ImageButton 
      android:id="@+id/c1" 
      android:layout_width="70dp" 
      android:layout_height="70dp" 
      android:layout_columnSpan="1" 
      android:layout_rowSpan="1" 
      android:background="@drawable/circle" 
      android:layout_margin="10dp" 
      /> 

我需要動態改變圓形狀的顏色,這將既可以做改變backgroundTint屬性的的ImageButton或更改圓形狀的顏色。

NOTE: 我有一串字符串存儲我需要使用這些RGB顏色的RGB顏色列表。

回答

1

我只是找到了答案,它的工作原理如下: 在我changeColors(INT ID)功能

  • 創建的ImageButton變量。
  • 將傳遞的id分配給ImageButton變量。
  • 定義GradientDrawable變量來存儲ImageButton背景。
  • 使用GradientDrawable變量更新背景的顏色。
  • 將ImageButton更新爲新的背景。

這是代碼:

ImageButton circle; 
     circle = (ImageButton) findViewById(id); 
     GradientDrawable drawable = (GradientDrawable) getResources().getDrawable(R.drawable.circle); 
     drawable.setColor(Color.parseColor("color in format #FFFFFF"); 
     circle.setBackground(drawable); 
1

你可以這樣說:

mImageView.setBackgroundTintList(getResources().getColorStateList(R.color.my_color)); 

或者你可以做的更好,支持的版本前LOLLIPOP:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) 
{ 
    ColorStateList stateList = ColorStateList.valueOf(getResources().getColor(R.color.my_color)); 
    mImageView.setBackgroundTintList(stateList); 
} 
else 
{ 
    mImageView.getBackground().getCurrent().setColorFilter(
      new PorterDuffColorFilter(getResources().getColor(R.color.my_color), 
      PorterDuff.Mode.MULTIPLY)); 
} 

更多PorterDuffColorFilter here

+0

有沒有辦法通過RGB顏色作爲字符串而不是 getResources()getColorStateList(R.color.my_color)。? 因爲我有一個存儲在字符串數組中的RGB列表,我需要使用他們 – Omar

+0

@Omar您最好將這些RGB顏色轉換爲int並將其傳遞給getColorStateList(int)方法。 – rogcg

+0

謝謝,我用另一種方法發佈它,感謝你的幫助 – Omar