2012-05-31 19 views
0

我的LinearLayout中有一些textViews。 他們是可點擊的,我想讓他們onClick像一個ListView。 對於listView,當用戶點擊一個項目時,背景變成綠色,我想。Android:在ListView中點擊設置TextView顏色

我知道,我可以

tv.SetBackgroundColor(Color.GREEN); 

手工做,但有一些automaticaly要做到這一點,像在選擇automaticaly管理列表視圖。

謝謝。

+0

默認情況下,listview是用這樣的特殊功能定義的。我認爲,我們不能做那的TextView .. –

+0

選中此[答案] [1] [1]:http://stackoverflow.com/questions/10713929/change-listview-item-background-on -click-android 它可以幫你 –

回答

1

您需要將背景定義爲包含狀態列表的新XML文件。

http://developer.android.com/guide/topics/resources/color-list-resource.html

例如,在你的文件夾繪製創建一個名爲background_states.xml文件,寫這樣的事:

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

然後定義這個新文件作爲背景在您的TextView:

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:background="@drawable/background_states" 

有關不同狀態的更多信息,請參閱上面的鏈接。

+0

這似乎是一個好主意。我有一個問題,我在xml文件中得到這個錯誤:錯誤:錯誤:找不到與給定名稱相匹配的資源(在'可繪製'值'@ Color/green')。 –

+0

格式@ color/color_name用於自定義顏色,它們必須在res/values/colors.xml文件中定義。如果你想使用Android預定義顏色,你應該寫@android:color/green –

+0

嗯,這不適合我,我在線性佈局中添加了dynamicaly(編程)TextViews。我的目標是每個電視,我使用tv.setBackgroundColor(R.drawable.background_states);但點擊後,沒有任何變化。 –

相關問題