2016-07-24 52 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); 
    } 
} 
相关问题