【发布时间】:2013-08-08 07:35:39
【问题描述】:
在我的自定义列表视图中,我使用了 relativelayout 并在其中垂直添加了 2 个文本视图。 背景图像设置为相对布局。现在我想在按下列表视图项时更改背景图像以及文本视图的文本颜色。 这个怎么弄,有大佬知道吗?
【问题讨论】:
标签: android listview listviewitem
在我的自定义列表视图中,我使用了 relativelayout 并在其中垂直添加了 2 个文本视图。 背景图像设置为相对布局。现在我想在按下列表视图项时更改背景图像以及文本视图的文本颜色。 这个怎么弄,有大佬知道吗?
【问题讨论】:
标签: android listview listviewitem
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/item_bg"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:textColor="@color/orange"
android:textSize="18sp"
android:textStyle="bold"
android:layout_marginTop="10dip"
android:layout_marginLeft="10dip"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="20dip"
android:layout_marginTop="8dip"
android:ellipsize="end"
android:maxLines="3"
android:duplicateParentState="true" <!-- this is a line to use..-->
android:textColor="@color/_textcolor"
android:textSize="14sp" >
</TextView>
res/drawable 文件夹中的item_bg.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" android:drawable="@drawable/bannerbg_hover"/>
<item android:state_focused="true" android:drawable="@drawable/bannerbg_hover" />
<item android:state_selected="true" android:drawable="@drawable/bannerbg_hover"/>
<item android:drawable="@drawable/bannerbg"/>
</selector>
_textcolor.xml 在 res/color/ 文件夹中:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" android:color="@color/white"/>
<item android:state_focused="true" android:color="@color/white" />
<item android:state_selected="true" android:color="@color/white"/>
<item android:color="@color/dark_blue"/>
</selector>
【讨论】:
关于背景,您应该创建一个StateList Drawable 并将其设置为行的背景。
此类可绘制对象的示例(可以命名为 background_selector.xml):
<?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/color1" /> <!-- pressed -->
<item android:drawable="@color/color2" /> <!-- default -->
</selector>
在你的行的布局声明中:
...
android:background="@drawable/background_selector"
...
使用与Color State List 相同的方式处理您的文本
【讨论】: