在网上也找了一些案例,但都是用Map来实现的.我的是把对象绑定到当前控件上.代码稍微简洁.
main布局文件:main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="horizontal" >
-
- <TextView
- android:id="@+id/tv"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_gravity="center_vertical" />
-
- <LinearLayout
- android:id="@+id/line"
- android:layout_width="fill_parent"
- android:layout_height="50dp"
- android:layout_below="@+id/tv"
- android:orientation="horizontal" >
-
- <Button
- android:id="@+id/bt_selectall"
- android:layout_width="80dp"
- android:layout_height="fill_parent"
- android:text="全选" />
-
- <Button
- android:id="@+id/bt_deselectall"
- android:layout_width="80dp"
- android:layout_height="fill_parent"
- android:text="取消选择" />
- </LinearLayout>
-
- <ListView
- android:id="@+id/lv"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:layout_below="@+id/line" />
-
- </RelativeLayout>
ListItem布局文件:listviewitem.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="horizontal" >
-
- <TextView
- android:id="@+id/item_tv"
- android:layout_width="0dp"
- android:layout_height="wrap_content"
- android:layout_gravity="center_vertical"
- android:layout_weight="1" />
-
- <CheckBox
- android:id="@+id/item_cb"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:clickable="false"
- android:focusable="false"
- android:focusableInTouchMode="false"
- android:gravity="center_vertical" />
-
- </LinearLayout>
实体类:Person.java
- package com.example.listview_checkbox;
-
- public class Person {
- private int id;
- private String name;
- private boolean selected;
-
- public Person(int id, String name, boolean selected) {
- super();
- this.id = id;
- this.name = name;
- this.selected = selected;
- }
-
- public int getId() {
- return id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public boolean isSelected() {
- return selected;
- }
-
- public void setSelected(boolean selected) {
- this.selected = selected;
- }
-
- }
MainActivity.java
效果图如下: