我是靠谱客的博主 烂漫溪流,最近开发中收集的这篇文章主要介绍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的状态来变化

这样就可以实现效果了。

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

使用系统的试过几个不知道哪里不对,一直没生效,这样写就可以了。

最后

以上就是烂漫溪流为你收集整理的ListView 点击Item的时候,改变文字颜色和背景色的全部内容,希望文章能够帮你解决ListView 点击Item的时候,改变文字颜色和背景色所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(42)

评论列表共有 0 条评论

立即
投稿
返回
顶部