如何处理 ExpandableListView 中的单选按钮?

How to handle Radio Button in ExpandableListView?

我有一个包含多于或等于 2 个组的 ExpandableListView。在这些组中,很少有带有单选按钮的项目。因此,当我 select 一组中的一个单选按钮时,不应 select 编辑另一组中的其他按钮。

以下代码有助于使单选按钮作为单选组工作。

@Override
public View getChildView(int groupPosition, final int childPosition,
                         boolean isLastChild, View convertView, ViewGroup parent) {

    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) this.mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.attribute_expanable_child_item, null);
    }

    RadioButton mRadioButton = convertView.findViewById(R.id.radio_option);
    mRadioButton.setVisibility(View.VISIBLE);
    mRadioButton.setText(mItem.getAttributeName());

    mRadioButton.setChecked(childPosition == selectedPosition);
    mRadioButton.setTag(childPosition);

    mRadioButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            selectedPosition = (Integer) view.getTag();
            notifyDataSetChanged();
        }
    });
}

现在,如果我 select 一个组中的一个项目,另一组中的另一个项目将 select 编辑在相同的位置!我知道我应该将 selected 位置保存在一个数组中,但我不知道如何保存。 那么,我应该怎么做才能在 ExpandableListView 中实现多个组?

我很久以前就找到了解决方案,但是忙于项目所以现在发布它,考虑到有人可以从中得到帮助!

为了在可展开的 ListView 中保持针对该特定组的选定位置,我必须保存该位置!所以我用HashMap保存了它。

所以在 hashmap 的第一个参数中,我存储了组位置和第二个视图的 ID。并在填充可扩展项的子项时设置它。

所以最终代码如下:

Hashmap<Integer, Integer> mChildCheckStates = new Hashmap<>();

@Override
public View getChildView(int groupPosition, final int childPosition,
                         boolean isLastChild, View convertView, ViewGroup parent) {

    final AttributePOJO mItem = (AttributePOJO) getChild(groupPosition, childPosition);
    String mGroup = (String) getGroup(groupPosition);

    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) this.mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.attribute_expanable_child_item, null);
    }

    RadioButton mRadioButton = convertView.findViewById(R.id.radio_option);
    mRadioButton.setVisibility(View.VISIBLE);

    try {
        mRadioButton.setChecked(childPosition == mChildCheckStates.get(groupPosition));

    }catch (Exception e){
        e.printStackTrace();
    }
    mRadioButton.setTag(childPosition);

    mRadioButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mChildCheckStates.put(groupPosition, (Integer) view.getTag());
            notifyDataSetChanged();
        }
    });

    return convertView;
}

就是这样!