Android 解決listview中checkBox錯位選擇


假如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對象。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM