您的位置:首页 > 其它

ListView 点击Item的时候,改变文字颜色和背景色

2014-06-10 13:51 751 查看
代码

list.xml

[java]
view plaincopy

<?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

[java]
view plaincopy

<?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用来做颜色变换

[java]
view plaincopy

<?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中

[java]
view plaincopy

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的状态来变化

这样就可以实现效果了。

不使用系统的,尽量自定义

使用系统的试过几个不知道哪里不对,一直没生效,这样写就可以了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: