ListView 點擊Item的時候,改變文字顏色和背景色

代碼

list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" 
    >

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    	/>

</LinearLayout>

list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" 
    android:background="@drawable/item_type" <!-- item背景色變換 -->
    >

    <TextView
        android:id="@+id/txt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" 
        android:layout_margin="5dp"
        android:textColor="@drawable/item_selector" <!-- item文字顏色變換 -->
    	/>

</LinearLayout>

再寫一個selector用來做顏色變換

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:color="@color/text_type02" /> <!-- focused -->
    <item android:state_pressed="true" android:color="@color/text_type02" /> <!-- pressed -->
    <item android:state_selected="true" android:color="@color/text_type02" /> <!-- pressed -->
    <item android:color="@color/text_type01" /> <!-- default -->
</selector>

然後到activity中

list = (ListView) findViewById(R.id.list);
        data = new ArrayList<HashMap<String, Object>>();
        for(int i=0; i<5; i++) {
        	map = new HashMap<String, Object>();
        	map.put("data", "Test" + i);
        	data.add(map);
        }
        
        SimpleAdapter simple = new SimpleAdapter(this, data, R.layout.list_item, new String[]{"data"},new int[]{R.id.txt});
        list.setAdapter(simple);

TextView 還要增加個屬性

android:duplicateParentState="true"

這樣纔會跟隨ParentView的狀態來變化

這樣就可以實現效果了。

不使用系統的,儘量自定義

使用系統的試過幾個不知道哪裏不對,一直沒生效,這樣寫就可以了。

發佈了28 篇原創文章 · 獲贊 6 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章