歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 完美解決Android在listview添加checkbox實現單選多選操作問題

完美解決Android在listview添加checkbox實現單選多選操作問題

日期:2017/3/1 10:48:22   编辑:Linux編程

在Android某些開發需求當中,有時候需要在listveiw中加入checkbox實現單選,多選操作。表面上看上去只是改變checkbox那麼簡單,然而實際開發中,實現起來並不是那麼得心應手。尤其當listview比較多(比如屏幕最多只能顯示10個item,但總共有12個item,也就是說listview的item數大於屏幕能夠顯示的item數)滑動屏幕的時候,由於適配器中getview()會重復使用被移除屏幕的item,所以會造成checkbox選擇狀態不正常的現象。自己在開發中碰到這樣的問題很是苦惱,查了下資料,發現網上很少沒有針對這類批量操作並沒有一個完整的例子。搜了很多篇帖子才完美的實現這一常用的操作。所以在這裡把這個Demo貼出來,供大家參考,希望能對大家有所幫助。

主界面的布局main.xml 這個就不多說什麼

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="wrap_content"
  5. android:orientation="vertical" >
  6. <LinearLayout
  7. android:orientation="vertical"
  8. android:layout_width="fill_parent"
  9. android:layout_height="wrap_content"
  10. >
  11. <TextView
  12. android:id="@+id/tv"
  13. android:layout_width="fill_parent"
  14. android:layout_height="50dip"
  15. android:textColor="#FCFCFC"
  16. android:textSize="11pt"
  17. android:gravity="center_vertical"
  18. android:layout_marginLeft="10dip"
  19. />
  20. <ListView
  21. android:id="@+id/lv"
  22. android:layout_width="fill_parent"
  23. android:layout_height="381dip"
  24. android:cacheColorHint ="#00000000"
  25. ></ListView>
  26. </LinearLayout>
  27. <RelativeLayout
  28. android:layout_width="fill_parent"
  29. android:layout_height="53dip"
  30. android:orientation="horizontal"
  31. >
  32. <Button
  33. android:id="@+id/selectall"
  34. android:layout_width="80dip"
  35. android:layout_height="50dip"
  36. android:layout_marginLeft="20dip"
  37. android:text="全選"
  38. android:gravity="center"
  39. />
  40. <Button
  41. android:id="@+id/inverseselect"
  42. android:layout_width="80dip"
  43. android:layout_height="50dip"
  44. android:layout_marginLeft="118dip"
  45. android:text="反選"
  46. android:gravity="center"
  47. />
  48. <Button
  49. android:id="@+id/cancel"
  50. android:layout_width="80dip"
  51. android:layout_height="50dip"
  52. android:layout_marginLeft="213dip"
  53. android:text="取消已選"
  54. android:gravity="center"
  55. />
  56. </RelativeLayout>
  57. </LinearLayout>
Copyright © Linux教程網 All Rights Reserved