如何在Android中选择一个时禁用组中的多个单选按钮?

时间:2015-07-13 16:00:45

标签: android android-radiogroup android-radiobutton

我在列表视图中有单选按钮,每列都会在最后添加一个单选按钮和一个复选框。但是用户应该只能在显示的列表中选择一个单选按钮,我试着在网上查看所有我可以获得如何使用已经由我完成的适配器列出单选按钮。谢谢。 以下是我的代码:

@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View view;
        ViewHolder holder;
        int selected;
        ListCollection person = items.get(position);
        if(convertView == null) {
            view = mInflater.inflate(R.layout.contact_adapter, parent, false);
            holder = new ViewHolder();
            holder.name = (TextView)view.findViewById(R.id.user_name);
            //holder.primary = (RadioButton) view.findViewById(R.id.primary_radio);
            holder.inVoice = (CheckBox) view.findViewById(R.id.checkBox1);
            holder.radioGroup = (RadioGroup) view.findViewById(R.id.radio_group);
            view.setTag(holder);
        } else {
            view = convertView;
            holder = (ViewHolder)view.getTag();
        }

        holder.name.setText(person.text);

        selected  = holder.radioGroup.getCheckedRadioButtonId();

        holder.radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // TODO Auto-generated method stub
                int childCount = group.getChildCount();
                 for (int x = 0; x < childCount; x++) {
                     RadioButton btn = (RadioButton) group.getChildAt(x);
                     if (btn.getId() == checkedId) {

                     }
                 }
            }
        });
            RadioButton button = new RadioButton(context);   
             button.setText("Primary");
             button.setid(i);
             holder.radioGroup.addView(button);
        return view;
    } 

2 个答案:

答案 0 :(得分:0)

我认为你的答案就在这里

How to use RadioGroup in ListView custom adapter?

答案 1 :(得分:0)

你需要做两件事:

  1. 使用mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
  2. 使您的自定义行视图实现可检查。