歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android中ListView結合CheckBox判斷選中項

Android中ListView結合CheckBox判斷選中項

日期:2017/3/1 11:03:11   编辑:Linux編程
本文主要實現在自定義的ListView布局中加入CheckBox控件,通過判斷用戶是否選中CheckBox來對ListView的選中項進行相應的操作。通過一個Demo來展示該功能,選中ListView中的某一項,然後點擊Button按鈕來顯示選中了哪些項。

[1] 程序結構圖如下:


其中Person.java是實體類,MainActivity.java是Activity組件類。listitem.xml是自定義的列表每項布局文件。

[2] listitem.xml布局文件源碼如下:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout
  3. xmlns:Android="http://schemas.android.com/apk/res/android"
  4. android:orientation="vertical"
  5. android:layout_width="fill_parent"
  6. android:layout_height="fill_parent">
  7. <LinearLayout
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content"
  10. android:orientation="horizontal"
  11. android:descendantFocusability="blocksDescendants">
  12. <CheckBox
  13. android:id="@+id/list.select"
  14. android:layout_width="wrap_content"
  15. android:layout_height="wrap_content"/>
  16. <TextView
  17. android:id="@+id/list.name"
  18. android:layout_width="fill_parent"
  19. android:layout_height="wrap_content"
  20. android:layout_weight="1"
  21. android:text="Name"
  22. android:layout_gravity="center"
  23. android:textSize="20dp"
  24. android:layout_marginLeft="10dp"/>
  25. <TextView
  26. android:id="@+id/list.address"
  27. android:layout_width="fill_parent"
  28. android:layout_height="wrap_content"
  29. android:layout_weight="1"
  30. android:text="Address"
  31. android:layout_gravity="center"
  32. android:textSize="20dp"/>
  33. </LinearLayout>
  34. </LinearLayout>
[3] main.xml布局文件源碼如下:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent">
  6. <Button
  7. android:id="@+id/show"
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content"
  10. android:text="Show"/>
  11. <ListView
  12. android:id="@+id/lvperson"
  13. android:layout_width="fill_parent"
  14. android:layout_height="fill_parent"/>
  15. </LinearLayout>
[4] Person.java實體類源碼如下:
  1. package com.andyidea.bean;
  2. public class Person {
  3. private String name;
  4. private String address;
  5. public String getName() {
  6. return name;
  7. }
  8. public void setName(String name) {
  9. this.name = name;
  10. }
  11. public String getAddress() {
  12. return address;
  13. }
  14. public void setAddress(String address) {
  15. this.address = address;
  16. }
  17. }
Copyright © Linux教程網 All Rights Reserved