2012-11-04 54 views
3

這是我第一次開發Android應用程序,所以這個問題可能是一件容易的事。 我想限制所選複選框的數量(即用戶應該只能選擇最多2個複選框)。我如何在onCheckedChanged()中做到這一點?如何限制在ListView中選中的框的數量

package com.mainak.walkbuddy; 

import java.util.List; 

import android.app.Activity; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ArrayAdapter; 
import android.widget.CheckBox; 
import android.widget.CompoundButton; 
import android.widget.TextView; 

public class InteractiveArrayAdapter extends ArrayAdapter<Model> 
{ 
    private final List<Model> list; 
    private final Activity context; 

    public InteractiveArrayAdapter(Activity context, List<Model> list) 
    { 
     super(context, R.layout.activity_show_content, list); 
     this.context = context; 
     this.list = list; 
    } 

    static class ViewHolder 
    { 
     protected TextView text; 
     protected CheckBox checkbox; 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) 
    { 
     View view = null; 
     int checkBoxCounter = 0;  
     int checkBoxInitialized = 0; 
     if (convertView == null) 
     { 
      LayoutInflater inflator = context.getLayoutInflater(); 
      view = inflator.inflate(R.layout.activity_show_content, null); 
      final ViewHolder viewHolder = new ViewHolder(); 
      viewHolder.text = (TextView) view.findViewById(R.id.label); 
      viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check); 
      viewHolder.checkbox.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() 
        { 
         @Override 
         public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
         { 
          Model element = (Model) viewHolder.checkbox.getTag(); 
          element.setSelected(buttonView.isChecked()); 
         } 
        } 
        ); 
      view.setTag(viewHolder); 
      viewHolder.checkbox.setTag(list.get(position)); 
     } 
     else 
     { 
      view = convertView; 
      ((ViewHolder) view.getTag()).checkbox.setTag(list.get(position)); 
     } 
     ViewHolder holder = (ViewHolder) view.getTag(); 
     holder.text.setText(list.get(position).getName()); 
     holder.checkbox.setChecked(list.get(position).isSelected()); 
     return view; 
    } 
} 

回答

1

添加表示檢查的項目數的int計數器,每當一個項目正在檢查您檢查計數器不大於2

更大的如果是大於2的話就不要做任何事情(不要設置標誌檢查),否則只需改變標誌並增加計數器。

而你應該設置onClickListener的視圖,並在那裏更改選中的標誌爲選中/未選中,然後調用notifydatasetchanged()更改選中的狀態。

因爲在添加onCheckedChangedListener時可能會有一些問題保持檢查狀態。

+0

我不明白在哪裏把int – user1742188

+0

把它作爲一個全局變量在async任務中,並且在構造函數裏面初始化它。 – meh

相關問題