代码
list.xml
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns: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
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns: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用来做颜色变换
- <?xmlversion="1.0"encoding="utf-8"?>
- <selectorxmlns:android="http://schemas.android.com/apk/res/android">
- <itemandroid:state_focused="true"android:color="@color/text_type02"/><!--focused-->
- <itemandroid:state_pressed="true"android:color="@color/text_type02"/><!--pressed-->
- <itemandroid:state_selected="true"android:color="@color/text_type02"/><!--pressed-->
- <itemandroid:color="@color/text_type01"/><!--default-->
- </selector>
然后到activity中
- list=(ListView)findViewById(R.id.list);
- data=newArrayList<HashMap<String,Object>>();
- for(inti=0;i<5;i++){
- map=newHashMap<String,Object>();
- map.put("data","Test"+i);
- data.add(map);
- }
- SimpleAdaptersimple=newSimpleAdapter(this,data,R.layout.list_item,newString[]{"data"},newint[]{R.id.txt});
- list.setAdapter(simple);
TextView 还要增加个属性
android:duplicateParentState="true"
这样才会跟随ParentView的状态来变化
这样就可以实现效果了。
不使用系统的,尽量自定义
使用系统的试过几个不知道哪里不对,一直没生效,这样写就可以了。
本文详细介绍了如何自定义Android中的ListView与TextView样式,并实现背景色、文字颜色随状态变化的效果。通过创建XML布局文件和使用Selector进行颜色变换,展示了如何利用自定义控件增强应用的用户体验。此外,还介绍了TextView的属性设置以使其跟随ParentView状态变化,提供了从布局设计到实际应用的完整解决方案。
9810

被折叠的 条评论
为什么被折叠?



