一次只选择Listview行中的一个单选按钮

时间:2013-12-17 14:26:25

标签: android android-listview radio-button android-arrayadapter

我正在尝试创建一个ListView,其行中只有RadioButton,一次只有一个选中项,所以没有多重选择。

以下是我到目前为止:(此代码仅确保单个选择,但是当列表首次加载时,列表的最后一项被选中,并且我也无法取消选中已选中的项目,只检查未选中一个 - 希望它足够清楚......)

关于我可能做错什么的任何想法?

public class GroupsAdapter extends ArrayAdapter<SchoolGroup> {

private boolean userSelected = false;
private RadioButton mCurrentlyCheckedRB;
private LayoutInflater mLayoutInflater;

public GroupsAdapter(Context context, List<SchoolGroup> objects) {
    super(context, 0, objects);
    mLayoutInflater = LayoutInflater.from(context);
}

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

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    final SchoolGroup schoolGroup = getItem(position);
    final GroupViewHolder groupViewHolder;
    if (convertView == null) {
        groupViewHolder = new GroupViewHolder();
        convertView = mLayoutInflater.inflate(R.layout.group_row, parent, false);

        if (convertView != null) {
            if (position % 2 != 0) {
                convertView.setBackgroundResource(R.drawable.bg_lighter);
            }
            groupViewHolder.checkedImg = (RadioButton) convertView.findViewById(R.id.group_checked_img);
            groupViewHolder.nameTxt = (CustomFontTextView) convertView.findViewById(R.id.group_name_txt);
            convertView.setTag(groupViewHolder);
        }
    } else {
        groupViewHolder = (GroupViewHolder) convertView.getTag();
    }

    if (position == getCount() - 1 && !userSelected) {
        groupViewHolder.checkedImg.setChecked(true);
        mCurrentlyCheckedRB = groupViewHolder.checkedImg;
    } else {
        groupViewHolder.checkedImg.setChecked(false);
    }

    if (convertView != null) {
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RadioButton button = ((RadioButton) v.findViewById(R.id.group_checked_img));
                if (mCurrentlyCheckedRB != null) {
                    if (mCurrentlyCheckedRB == null)
                        mCurrentlyCheckedRB = button;
                    LoginActivity.selectedGroup = getItem(position);
                    mCurrentlyCheckedRB.setChecked(true);
                }

                if (mCurrentlyCheckedRB == button)
                    return;

                if (mCurrentlyCheckedRB != null) {
                    mCurrentlyCheckedRB.setChecked(false);
                }

                button.setChecked(true);
                mCurrentlyCheckedRB = button;
            }
        });
    }
    groupViewHolder.nameTxt.setText(schoolGroup.getName());
    return convertView;
}

private static class GroupViewHolder {
    RadioButton checkedImg;
    CustomFontTextView nameTxt;
}

}

0 个答案:

没有答案