9

我希望我的 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>
4

3 回答 3

23

将此设置为您的 TextView:

android:clickable="true"
于 2012-11-08T22:04:44.670 回答
9

添加

android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
于 2012-11-08T22:01:43.453 回答
4

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

// From the View class.
public void setOnClickListener(OnClickListener l) {
    if (!isClickable()) {
        setClickable(true);
    }
    getListenerInfo().mOnClickListener = l;
}
于 2012-11-08T22:08:07.957 回答