在选择器中更改可绘制对象的颜色

3

能否在选择器中改变drawable的颜色?

我的选择器:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/ic_plus_circle_grey600_48dp" android:state_pressed="true"/>
    <item android:drawable="@drawable/ic_plus_circle_black_48dp"/>
</selector>

我尝试使用这种方法(在这种情况下,我正在使用tint选择器),但我遇到了一些错误:
<ImageView
     android:id="@+id/btAdd"
     android:layout_width="wrap_content"
     android:src="@drawable/ic_plus_circle_black_48dp"
     android:tint="@color/blue_android_focused"
     android:layout_height="wrap_content"/>

这是色调选择器的选择器:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/blue_android_pressed" android:state_pressed="true" />
    <item android:color="@color/green" />
</selector>
3个回答

15

使用位图上的色调(** API 21+ **):

选择器:drawable/selector_add

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <bitmap android:src="@drawable/ic_plus_circle_grey600_48dp"
            android:tint="@color/blue_android_pressed" />
    </item>
    <item>
        <bitmap android:src="@drawable/ic_plus_circle_grey600_48dp"
            android:tint="@color/colorAccent" />
    </item>
</selector>

ImageView
<ImageView
    android:id="@+id/btAdd"
    android:layout_width="wrap_content"
    android:src="@drawable/selector_add"
    android:layout_height="wrap_content"
    />

在xml的选择器上出现了错误,错误信息为"属性缺少Android命名空间前缀",具体是在name="android:drawable"处。而且当我运行时,在使用这个选择器进行布局填充的活动中也出现了错误。 - undefined
这是我使用的示例项目,你可以在这里尝试它:https://www.dropbox.com/sh/5jexf0u1z5jw8i4/AABHy7gKUOBMiAPXrs6i7G0Ba?dl=0 - undefined
10
只有当drawable为png格式时,这才有效,而不是XML格式。 - undefined

-1
你可以使用不同的颜色来绘制相同的可绘制对象,这对我来说很有效。

enter image description here


我不想为每种颜色都创建一个图像,因为这是一张图片。 - undefined
你想通过选择器来改变可绘制图像的颜色吗? - undefined
是的,像这样 <ImageView android:tint="@color/blue_android_pressed" android:src="@drawable/ic_close_circle_black_48dp"> 但使用选择器 - undefined

-2
你应该像这样使用tint:
<ImageView
android:id="@+id/activity_register_et_fullname"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/bg_page"
app:backgroundTint="@color/blue_android_focused"/>

在`AppCompatActivity`中使用`ImageView`,它将被充气成`AppCompatImageView`(另请参阅`android.support.v7.app.AppCompatViewInflater`)。你应该看一下其中的代码。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接