Android实现LIstView条目单选和多选RadioButton

看效果图是不是你想要的

Android实现LIstView条目单选和多选RadioButton

ListView的布局

<ListView
    android:choiceMode="singleChoice"
    android:background="#fff"
    android:layout_marginTop="5dp"
    android:id="@+id/listview_template"
    android:layout_above="@id/ll"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
其中choiceMode的属性很重要 选择模式.再没有发现这个属性的时候,我们一般会把选中的添加到一个Map中(position,true或false),然后在取出值进行判断是否有选中,

ListView的选择模式有4中分别是

1,CHOICE_MODE_NONE 普通模式

2,CHOICE_MODE_SINGIE 单选模式

3,CHOICE_MODE_MULTIPLE 多选模式

4,CHOICE_MODE_MULTIPLE_MODAL 多选模式

也可以在代码中设置这4个属性值

mListView.setChoiceMode(ListView.CHOICE_MODE_SINGIE);

下面是item的布局里面包含一个RadioButton

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:paddingTop="7dp"
                android:paddingBottom="7dp"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
    <TextView
        android:layout_marginLeft="12dp"
        android:textSize="@dimen/textSize_Eighteen"
        android:id="@+id/template_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:text="模板1"/>
    <RadioButton
        android:checked="false"
        android:clickable="false"
        android:focusableInTouchMode="false"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:focusable="false"
        android:layout_gravity="center_vertical"
        android:layout_marginRight="12dp"
        android:id="@+id/chickbutton"
        android:button="@drawable/chickbox_quipment_bg_selector"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</RelativeLayout>
getView方法

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = View.inflate(SelectWatermarkActivity.this, R.layout.view_template, null);
    }
    TextView name = (TextView) convertView.findViewById(R.id.template_name);
    final RadioButton radioButton = (RadioButton) convertView.findViewById(R.id.chickbutton);
    if (selectPosition == position) {
        radioButton.setChecked(true);
    } else {
        radioButton.setChecked(false);
    }
    TemplateBean.ResponseBean bean = mResponse.get(position);
    name.setText(bean.getTemplateName());
    return convertView;
}
其中selectPosition是用户选择条目的变量

再用户点击条目的时候进行初始化

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    selectPosition = position;
    mAdapter.notifyDataSetChanged();

}
好了使用choiceMode属性可以很简单的实现单选和多选功能