Android:为什么我无法为TextView背景使用选择器?

3
我的选择器是:

<item android:state_pressed="true" android:color="@color/bg_grey"/>
<item android:state_focused="true" android:color="@color/bg_grey"/>
<item android:color="@color/white"/>

我有一个TextView:

    <TextView
        android:id="@+id/tv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:background="@drawable/textview_selector"
        android:padding="5dp"
        android:text="Some Text"
        android:textColor="@color/text_grey"
        android:textSize="16dp" />
我正在获得以下内容:
android.view.InflateException: Binary xml file line #68: Error inflating class <unknown>

如果我使用此选择器,如 android:textColor="@drawable/textview_selector" ,它可以正常工作。

3个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
10

这里的问题在于不能使用颜色选择器来定义背景颜色,需要使用可绘制选择器。因此,必要的更改如下:

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

为了更合理,您还需要将该资源移动到drawable目录中,因为它本身并不是一个颜色选择器。

然后,您需要创建res/drawable/selected_state.xml文件,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">
    <solid android:color="@color/bg_grey" />
</shape>

最后,您可以像这样使用它:

android:background="@drawable/selector"

1

您正在选择器 XML 中将颜色定义为背景 Drawable,建议尝试使用背景 Drawable。


0

你只需要确保颜色在colors.xml文件中,并且不要直接将十六进制颜色放入选择器项中。

my_selector.xml:

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

并使您的TextView看起来像这样:

 <TextView
    android:id="@+id/tv_name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:letterSpacing="0.05"
    android:textColor="#000000"
    android:gravity="center"
    android:textSize="17sp"
    tools:text="New In"
    android:clickable="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:background="@drawable/my_selector"
    android:layout_gravity="center"
    />

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