您的位置:首页 > 其它

listview中如何通过selector改变点击时的背景色

2015-12-22 20:04 489 查看
如题:主要讲述如何通过selector来改变listviewe中点击item后背景色的改变。

(1)编写selector,这里主要介绍下如何在android studio中新建selector。主要步骤如下所述:

找到你项目的res目录,右键->new->android resource file->



然后点击 resource type,选择Drwable,并在file name指定selector的名字,这里我们命名成listview_selector。如下图所示:



这个时候你就可以在你的res/drawable目录下看到你的selector.

(2)selector具体的内容如下:

<?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/q"/>
<item android:drawable="@drawable/p"/>
</selector>


(3)贴出activity_main.xml中的布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<ListView
android:id="@+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#565C5D"
android:dividerHeight="3dp"
android:listSelector="@drawable/listview_color_selector"
>
</ListView>
</RelativeLayout>

注意其中有一项属性是:

android:listSelector="@drawable/listview_color_selector"(实际上是我们刚刚创建的listview_selector,注意改下名字)如果你是已图片背景的形式改动需要添加这一句,如果只是更改背景颜色则不需要。

至此就完成啦。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: