簡體   English   中英

在列表視圖中處理選中然后未選中的復選框的值

[英]Handle checked and then unchecked checkbox's value in listview android

在我的活動中,列表視圖中有4個項目,每行都有一個復選框。 離開活動后,我希望所有選中的項目位置編號都在arraylist中。 當用戶單擊所有復選框並退出活動時,此代碼可以正常工作。 但是,當用戶單擊復選框然后取消選中該復選框時,arraylist的項目位置無法清除。 這種情況在我的CustomAdapter類中。

class GameAdapter extends BaseAdapter{
      private ArrayList<Integer> positions = new ArrayList<Integer>();

      public ArrayList<Integer> getPositions() {
          return positions;
      }

      getView(....){
         final ViewHolder holder;
         holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if(holder.checkBox.isChecked()) {

                    positions.add(position);

                }
            }
        });
    }
}

我在我的listview所在的活動中處理此適配器類。 我在這里采用這樣的arraylist值

ArrayList<Integer> gamePositions = mGameAdapter.getPositions();
String itemNumbers = gamePositions.toString();

在itemNumber字符串中,我需要所有檢查的項目編號值。

預先感謝您的指導。

請遵循以下方法。

  • 使用HashMap代替Arraylist,如下所示

      HashMap<Integer,Boolean> mapOfSelection = new HashMap<>(); 
  • onClick方法之前,將position分配給復選框,如下所示。

      holder.checkbox.setTag(position); 
  • 在onClick中,執行以下操作。

      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mapOfSelection.put((Integer)buttonView.getTag(),isChecked); // True if this position/value is checked, false otherwise. } 
  • 現在,當您需要選定的項時,只需遍歷哈希圖並檢查具有True值的positions/Key

取代這個

if(holder.checkBox.isChecked()) {

  positions.add(position);
}

有了這個

 if(holder.checkBox.isChecked()) {
     if(!positions.contains(position))
        positions.add(position);

 } else {
     if(positions.contains(position))
         positions.remove(position);

 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM