ListView中限制选择(checkbox)数目的Adapter


public class MyListAdapter extends BaseAdapter {

    private String[] dataString;
    private LayoutInflater inflater;
    private ArrayList listBoolean;
    private int count = 0;
    private int maxChecked;
    private Context context;


    public MyListAdapter(Context contexts, String[]strings, ArrayList listBooleans,int maxCheck){
        this.dataString = strings;
        this.listBoolean = listBooleans;
        this.context = contexts;
        this.maxChecked = maxCheck;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return dataString.length;
    }

    @Override
    public Object getItem(int i) {
        return dataString[i];
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {

        final ViewHolder viewHolder;

        if (null == view){
            viewHolder = new ViewHolder();
            view = inflater.inflate(R.layout.list_item,null);
            viewHolder.img = (ImageView)view.findViewById(R.id.showImage);
            viewHolder.title = (TextView)view.findViewById(R.id.showContent);
            viewHolder.checkBox = (CheckBox)view.findViewById(R.id.showCheckBox);
            view.setTag(viewHolder);
        }else{
            viewHolder = (ViewHolder)view.getTag();
        }
        viewHolder.img.setImageResource(R.drawable.easypicture);
        viewHolder.title.setText(dataString[i]);
        viewHolder.checkBox.setChecked(listBoolean.get(i));
        viewHolder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //实现功能的主要部分
         if (viewHolder.checkBox.isChecked()){
                    count++;
                    listBoolean.set(i,true);
                }else if (!viewHolder.checkBox.isChecked()){
                    count--;
                    listBoolean.set(i,false);
                }
               //进行判断
                if (count > maxChecked){
                    viewHolder.checkBox.setChecked(!viewHolder.checkBox.isChecked());
                    count--;
                    listBoolean.set(i,false);
                    Toast.makeText(context,"超过设定值",Toast.LENGTH_LONG).show();
                }
                Log.i("----->",listBoolean.toString());
            }
        });
        return view;
    }
    class ViewHolder{
        public ImageView img;
        public TextView title;
        public CheckBox checkBox;
    }
}

你可能感兴趣的:(开发笔记,ListView,CheckBox,限制选择数目,Adapter)