歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android 解決listview中checkBox錯位選擇

Android 解決listview中checkBox錯位選擇

日期:2017/3/1 11:08:20   编辑:Linux編程

假如ListView,分成2頁(或者設置數據可以縱向拉,可隱藏),每頁3條數據,每個Listview的Item 裡面有個checkBox,現在,當我選擇第一頁的前兩天數據,翻到第二頁,竟然第二頁後兩條數據也選中了,這是絕對不允許的。經過本人的N次調試,發現public View getView(int position, View convertView, ViewGroup parent)傳進來的convertView 竟然產生多次重用。解決方案:當選中checkedBox時候,我們用一個List來保存該checkBox的position。然後在每次產生View時取得傳來的convertView賦值為null,再遍歷List裡保存的checkBox的位置,當在數組內時,checkBox置為選中,問題解決了。

該問題有兩種解決方案,個人目前所實現了的。

1.用HashMap保存checkbox的狀態值。

HashMap<Integer, Boolean> state = new HashMap<Integer,Boolean>();

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked)
{
state.put(position, isChecked);
System.out.println("復選框以選中,選中的行數為:" + temp_position);
}else{
state.remove(position);
}
}

在getView()方法裡面: holder.cbox.setChecked(state.get(position)==null? false : true);

2.(不推薦使用,因為會產生許多垃圾對象)

public View getView(int position, View convertView, ViewGroup parent)在每次傳進convertView時候,設為null。

然後每調用一次getView就產生一個view對象。

Copyright © Linux教程網 All Rights Reserved