本文主要实现在自定义的ListView布局中加入CheckBox控件,通过判断用户是否选中CheckBox来对ListView的选中项进行相应的操作。通过一个Demo来展示该功能,选中ListView中的某一项,然后点击Button按钮来显示选中了哪些项。
[1] 程序结构图如下:
其中Person.java是实体类,MainActivity.java是Activity组件类。listitem.xml是自定义的列表每项布局文件。
[2] listitem.xml布局文件源码如下:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <LinearLayout
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:orientation="horizontal"
- android:descendantFocusability="blocksDescendants">
- <CheckBox
- android:id="@+id/list.select"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"/>
- <TextView
- android:id="@+id/list.name"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:text="Name"
- android:layout_gravity="center"
- android:textSize="20dp"
- android:layout_marginLeft="10dp"/>
- <TextView
- android:id="@+id/list.address"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:text="Address"
- android:layout_gravity="center"
- android:textSize="20dp"/>
- </LinearLayout>
- </LinearLayout>
[3] main.xml布局文件源码如下:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <Button
- android:id="@+id/show"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="Show"/>
- <ListView
- android:id="@+id/lvperson"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"/>
- </LinearLayout>
[4] Person.java实体类源码如下:
- package com.andyidea.bean;
-
- public class Person {
-
- private String name;
- private String address;
-
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getAddress() {
- return address;
- }
- public void setAddress(String address) {
- this.address = address;
- }
-
- }
[5] MainActivity.java类源码如下:
[6] 程序运行后的结果如下:
http://blog.csdn.net/cjjky/article/details/6967219
Android中ListView结合CheckBox判断选中项
原文:http://www.cnblogs.com/cmblogs/p/4347892.html