在Android上更改ImageView的BackgroundTint

时间:2016-06-27 19:24:04

标签: java android xml

我有一个ImageButton,它有一个可绘制的背景资源,它是椭圆形的。

<?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"
            />

我需要动态更改圆形的颜色,这可以通过更改ImageButton中的backgroundTint属性或更改圆形颜色来完成。

注意: 我有一些字符串数组,用于存储我需要使用这些RGB颜色的RGB颜色列表。

3 个答案:

答案 0 :(得分:2)

你可以这样做:

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的更多信息。

答案 1 :(得分: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);

答案 2 :(得分:0)

您可以改用 ImageView 并使用 app:tint 设置可绘制背景的色调颜色。

<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:src="@drawable/circle"
app:tint="@android:color/holo_red_dark"/>