最近做一个项目需要实现listview的item单选效果,一开始很自然的想到在布局文件中加RadioButton,然后在适配器里控制它的选中状态。在开发的过程中,却是遇到意想不到的问题:RadioButton的事件跟item的点击事件冲突,在百度上始终没有找到完美的解决方案,搞了大半天还是没解决。后来隐约记得apidemo里有类似的效果,于是找到它的源码布局文件研究,原来它使用的是CheckedTextView控件,研究了一翻,这个问题才完美解决。下面记录下关键布局文件:
item的layout文件:
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="@style/style_14_333333"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checkMark="@drawable/rb_bg_x"
android:gravity="center_vertical"
android:paddingBottom="6dip"
android:paddingLeft="14dip"
android:paddingRight="14dip"
android:paddingTop="6dip" />
android:checkMark属性指定显示选中与未选中状态的图片
列表布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@drawable/bg_layer"
>
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#00000000"
android:choiceMode="singleChoice"
android:divider="@drawable/list_line"
android:background="@drawable/bg_r"
>
</ListView>
</LinearLayout>
android:choiceMode="singleChoice"属性指定单选或多选
效果如下: