2010-06-04 189 views
7

我已經搜索了interwebs,並發現了許多關於如何使用列表選擇器更改列表視圖顏色的文章。但它似乎並不適合我。所以我的問題是我做錯了什麼?自定義Android ListView顏色?

當我使用下面的文件時,我得到一個列表,其中所有項目背景最初都是藍色的。 (我期望白色)

當我上下移動焦點時,文本變成深灰色,並且項目背景仍然是藍色。 (這是當我期望一行是藍色的,其餘的是白色的)

當我點擊一行時,單擊的行的背景變成黑色,其他所有行變成綠色。 (我希望有我點擊變綠行,其餘是白色)

這是我的主要佈局文件:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
<ListView 
    android:id="@android:id/list" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:listSelector="@drawable/item_selector" 
    /> 
<TextView 
    android:id="@android:id/empty" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/empty" 
    /> 
</LinearLayout> 

這裏是我的列表項文件:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="horizontal" 
    android:padding="10sp"> 
    <CheckBox 
     android:id="@+id/checkbox" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:focusable="false" 
     /> 
    <TextView 
     android:id="@+id/title" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:ellipsize="end" 
     android:singleLine="true" 
     android:textStyle="bold" 
     android:padding="7dip" 
     android:textSize="18sp" 
     android:layout_toRightOf="@id/checkbox" 
     /> 
</RelativeLayout> 

這裏我的色彩文件:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <color name="red">#ff00</color> 
    <color name="green">#f0f0</color> 
    <color name="blue">#f00f</color> 
    <color name="white">#ffff</color> 
</resources> 

這是我選擇的文件:

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

希望這是愚蠢和簡單的,我做錯了。

在此先感謝。

+0

它聽起來像整個listView本身正在集中,而不是單個列表項。 – YGL 2010-06-04 13:50:46

回答

7

我認爲android:listSelector =「@ drawable/item_selector」僅適用於視圖的根目錄,而不是他的子目錄。

嘗試添加@繪製/ item_selector爲您的RelativeLayout與android:background="@drawable/item_selector"一個背景與放一個透明的佈局到listSelector:

android:listSelector="@android:color/transparent" 
+0

這是勝利的組合。謝謝!現在已經掙扎了好幾天了。 – 2010-06-04 16:48:19

+0

很好,謝謝:) – ademar111190 2012-08-08 15:05:22

1

其實,如果你想以編程方式做到這一點,而無需使用資源,你可以設置你的元素的顏色。例如,設置文本顏色#F123456在TextView

objTextView.setTextColor(color.parseColor("#F12345")); 

這是方便,如果你想動態設置列表視圖的顏色是用戶可選擇的,也許是存儲在數據庫中,你根本不能使用顏色列表的靜態資源文件。