【问题标题】:Android: How to use selector for background of a TextView?Android:如何使用选择器作为 TextView 的背景?
【发布时间】:2012-10-29 04:39:09
【问题描述】:

我希望我的 TextView 在按下时使用不同颜色的背景进行绘制。下面的 xml 包含一个 Button 和 TextView,它们都指定一个 Selector 作为它们的背景。 Button 按预期工作,但 TextView 在按下时不会改变颜色。有没有办法让 TextView 工作?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView 
        android:text="temporary text view"
        android:layout_width="wrap_content"
        android:layout_height="100dip"
        android:background="@drawable/blackselector"
        />    
    <Button
        android:text="temporary button"
        android:layout_width="wrap_content"
        android:layout_height="100dip"
        android:background="@drawable/blackselector"
        />   
</LinearLayout>

选择器.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <color android:color="#FF0000" />
    </item>
    <item>
        <color android:color="#00FF00" />
    </item>
</selector>

【问题讨论】:

    标签: android


    【解决方案1】:

    上面关于将clickable设置为true的内容是正确的。此外,如果您添加一个 onClickListener,Android 会自动为您设置 clickable 为 true。

    // From the View class.
    public void setOnClickListener(OnClickListener l) {
        if (!isClickable()) {
            setClickable(true);
        }
        getListenerInfo().mOnClickListener = l;
    }
    

    【讨论】:

      【解决方案2】:

      将此设置为您的 TextView:

      android:clickable="true"
      

      【讨论】:

      • 有趣的是我的答案之前是如何发布的,但没有被接受。嗯。
      • @PaulBurke 是的,我也想知道。但在我的辩护中,我在发布我的答案时没有看到其他答案。我猜 ab11 没有注意到之前发布的答案。但我确实赞成你的。
      • 不用担心。显然不是你的错(我实际上打算对这个问题发表评论)。感谢您的支持! :-)
      【解决方案3】:

      添加

      android:clickable="true"
      android:focusable="true"
      android:focusableInTouchMode="true"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-11
        相关资源
        最近更新 更多