2012-11-08 30 views
8

我希望我的TextView在按下时用不同的颜色背景进行绘制。下面的xml包含一个Button和TextView,它们都将Selector指定为它们的背景。该按钮按预期工作,但TextView在按下时不会改变颜色。有没有办法让这个工作的TextView?Android:如何使用选择器作为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> 

selector.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> 

回答

21

将其设置为你的TextView:

android:clickable="true" 
+1

有趣的是我的回答是如何发布的,但没有被接受。嗯。 –

+0

@PaulBurke是的,我也在想。但在我的辩护中,我没有看到在我发布我的时候还有其他答案。我猜ab11没有注意到早些时候发布了哪个答案。但我确实鼓励了你的。 – Ahmad

+2

不用担心。显然不是你的错(我实际上打算评论这个问题)。感谢upvote! :-) –

9

添加

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

上述有关设置点击为真是正确的。此外,如果您添加onClickListener,则Android会自动将您的clickable设置为true。

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