Android - 更改可绘制对象的颜色

Android - Change color of Drawables

我有一个选择器,我在其中设置了一个圆圈作为 state_selected = true 的背景,但我想在单击该对象时更改颜色。我该怎么做?

这是我的可绘制对象的设置方式:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#D0021B"/>
<stroke android:width="2dp" android:color="#910012" />
<size
    android:width="50dp"
    android:height="50dp" />
<corners android:radius="50dp" />
</shape>

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/black" android:state_selected="false" />
<item android:drawable="@drawable/nav_circle" android:state_selected="true" />
</selector>

如果你想在按下的那一刻改变颜色,你可以使用state_pressed。

<item android:state_pressed="true"
      android:drawable="@color/pressedColor"/> <!-- pressed state -->
<item android:state_focused="true"
      android:drawable="@color/pressedColor"/> <!-- focused state -->
<item android:drawable="@color/colorPrimary"/>

你也可以在 android:drawable 属性下使用另一个 drawable

<item android:state_pressed="true"
      android:drawable="@drawable/button_solid"/>

但是,如果您想在按下时更改背景可绘制对象,您可以将按钮背景更改为不同的 xml 可绘制对象

button.setBackground(getDrawable(R.drawable.selectorDrawable2));

也许这会对你有所帮助:

i=(ImageView)findViewById(R.id.image);
    i.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            i.getBackground().setColorFilter(Color.BLUE, PorterDuff.Mode.SRC_ATOP); 
        }
    });

ImageView xml 代码:

<ImageView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:background="@drawable/nav_circle"
   android:layout_centerVertical="true"
   android:layout_centerHorizontal="true"
   android:id="@+id/image" />

您可以通过编程方式完成:

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);
            }
        }

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
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);
    }
}