歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 解決 Android 中使用ListView和CheckBox批量操作時若干問題

解決 Android 中使用ListView和CheckBox批量操作時若干問題

日期:2017/3/1 10:27:04   编辑:Linux編程

本文可以幫助 完美解決 在Android中使用ListView時批量操作CheckBox出現的各種問題。

在Android中使用ListActivity可以很方便的綁定一組數據或者一個查詢。但是,使用過程中也會遇到一些問題。在此,我將自己遇到的問題以及解決方法記錄下來,一方面做一個備忘,同時,也希望有緣人能少走彎路。

問題一: Listview中的Item數目到底是多少

ListView中的Item數目可以使用getCount方法獲得,經過驗證得到的結果是,其Item數目等於界面上顯示的Item數目,這個數目可能小於實際上綁定的數據條目數。

那麼,在實際中如果有額外的非綁定數據源的數據需要編輯保存的時候,如何才能保存他們呢?

解決該問題的方法是:自定義ListAdapter,在其中保存額外需要保存的數據。

問題二:在Item中添加CheckBox出現麻煩了

在item中添加Checkbox的時候不小心會遇到麻煩,可能出現的情況是:

(1)Listview不能相應點擊事件

(2)Listview點擊第一個Item的時候最後一個Item也出現點擊事件(反之亦然)

以上兩種情況是我實際遇到的bug,經過各種糾結和反復測試,出現問題的原因是CheckBox相應焦點、點擊事件的優先級別比Listview要高,所以出現問題。

解決方法如下(和問題一一對應):

(1)將Checkbox設置focusable屬性為false

(2)接著將CheckBox設置Clickable屬性為false.

以下是本人程序片段,僅供參考:

  1. <!-- ans_list.xml -->
  2. <?xml version="1.0" encoding="utf-8"?>
  3. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. android:paddingLeft="8dp"
  7. android:paddingRight="8dp" >
  8. <TextView
  9. android:id="@+id/ans_title"
  10. android:layout_width="fill_parent"
  11. android:layout_height="wrap_content"
  12. android:layout_alignParentTop="true"
  13. android:gravity="center"
  14. android:textSize="15sp"
  15. android:textStyle="bold" />
  16. <RelativeLayout
  17. android:id="@+id/ans_foot"
  18. android:layout_width="fill_parent"
  19. android:layout_height="wrap_content"
  20. android:layout_alignParentBottom="true"
  21. android:paddingLeft="8sp"
  22. android:paddingRight="8sp" >
  23. <CheckBox
  24. android:id="@+id/ans_cbx_select"
  25. android:layout_width="wrap_content"
  26. android:layout_height="wrap_content"
  27. android:layout_alignParentRight="true"
  28. android:layout_marginLeft="10sp"
  29. android:checked="false" />
  30. <Button
  31. android:id="@+id/ans_btn_showInMap"
  32. android:layout_width="fill_parent"
  33. android:layout_height="wrap_content"
  34. android:layout_toLeftOf="@id/ans_cbx_select"
  35. android:text="@string/ans_btn_showInMap" />
  36. </RelativeLayout>
  37. <ListView
  38. android:id="@android:id/list"
  39. android:layout_width="fill_parent"
  40. android:layout_height="fill_parent"
  41. android:layout_above="@id/ans_foot"
  42. android:layout_below="@id/ans_title"
  43. android:drawSelectorOnTop="false" >
  44. </ListView>
  45. <TextView
  46. android:id="@android:id/empty"
  47. android:layout_width="fill_parent"
  48. android:layout_height="fill_parent"
  49. android:gravity="center"
  50. android:text="@string/ans_list_empty"
  51. android:textSize="25sp"
  52. android:textStyle="bold" >
  53. </TextView>
  54. </RelativeLayout>
Copyright © Linux教程網 All Rights Reserved