设置TextView Drawable的颜色

时间:2017-04-12 12:25:32

标签: android xamarin xamarin.android

我试图改变Xamarin中TextView Drawable的颜色。

在Java中你可以这样做:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    TextView txt = (TextView) findViewById(R.id.my_textview);
    setTextViewDrawableColor(txt, R.color.my_color);
}

private void setTextViewDrawableColor(TextView textView, int color) {
    for (Drawable drawable : textView.getCompoundDrawables()) {
        if (drawable != null) {
            drawable.setColorFilter(new PorterDuffColorFilter(getColor(color), PorterDuff.Mode.SRC_IN));
        }
    }
}

我如何在Xamarin.Android中做这样的事情?

7 个答案:

答案 0 :(得分:9)

尝试以下解决方案

defaultValue

答案 1 :(得分:9)

请注意,如果通过android:drawableStartandroid:drawableEnd而不是android:drawableLeftandroid:drawableRight在布局文件中设置可绘制对象,则应使用TextView.getCompoundDrawablesRelative()。否则,您将获得可绘制对象的空数组。

private void setTextViewDrawableColor(TextView textView, int color) {
    for (Drawable drawable : textView.getCompoundDrawablesRelative()) {
        if (drawable != null) {
            drawable.setColorFilter(new PorterDuffColorFilter(ContextCompat.getColor(textView.getContext(), color), PorterDuff.Mode.SRC_IN));
        }
    }
}

答案 2 :(得分:4)

// index of drawable
val left = 0
val start = left
val top = 1
val right = 2
val end = right
val bottm = 3

// color int
val color = Color.RED

// apply tint for target drawable
textView.compoundDrawables.getOrNull(left)?.setTint(color)

// apply tint for all drawables
textView.compoundDrawables?.forEach { it?.setTint(color) }

注意!

如果在XML布局中使用android:stratDrawableandroid:endDrawable,则必须使用textView.compoundDrawablesRelative数组,则textView.compoundDrawables将包含与android:leftDrawable添加的可绘制对象或android:rightDrawable属性。

答案 3 :(得分:1)

如果要更改任何视图的可绘制对象的着色颜色(在API 29上测试):

private fun setTintColor(textView: TextView, color: Int) {

    DrawableCompat.setTint(DrawableCompat.wrap(textView.background).mutate(), 
    ContextCompat.getColor(this, color))

}

答案 4 :(得分:0)

我在kotlin中使用它:

tv.getCompoundDrawables()[0].setTint(//color)

答案 5 :(得分:0)

我通过在以下行中的xml定义中解决此问题:

android:drawableTint =“ @ color / red”

完整的示例:

        <TextView
            android:id="@+id/tv_element"
            android:layout_width="wrap_content"
            android:layout_height="20dp"
            android:layout_alignParentEnd="true"
            android:drawableStart="@drawable/ic_icon"
            android:drawableTint="@color/color"
            android:visibility="visible" />

答案 6 :(得分:0)

对于Kotlin。对 TextView 可绘制对象使用以下扩展名。它支持低于和高于 23 的 API 级别。

    private fun TextView.setTextViewDrawableColor(color: Int) {
        for (drawable in this.compoundDrawablesRelative) {
            drawable?.mutate()
            drawable?.colorFilter = PorterDuffColorFilter(
                color, PorterDuff.Mode.SRC_IN
            )
        }
    }

注意:您也可以在RecyclerView项中使用此功能,它不会为每个项override相同的颜色