3

这是我第一次开发 Android 应用程序,所以这个问题可能是显而易见的。我想限制所选复选框的数量(即,用户应该只能选择最多 2 个复选框)。如何在 onCheckedChanged() 中执行此操作?

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;
    }
} 
4

1 回答 1

1

添加一个表示检查项目数的 int 计数器,每次检查项目时,您检查计数器是否不大于 2。

如果它大于 2 则不做任何事情(不要将标志设置为选中),否则只需更改标志并增加计数器。

您应该将 onClickListener 设置为视图并将选中标志更改为选中/未选中,然后调用 notifydatasetchanged() 来更改选中状态。

因为在添加 onCheckedChangedListener 时保持选中状态可能会出现一些问题。

于 2012-11-04T21:34:42.977 回答