Using radio button in custom listview in Android

核能气质少年 提交于 2019-12-04 16:12:12
Nikita Beloglazov

One way is to manually uncheck all others radiobuttons. You can create variable that will keep position of currently selected item. And in getView you check/uncheck current radio button depending on whether current position equals to selected one. When use press radio button you change position of selected item and call notifyDatasetChanged.
Also check this quesion: Android ListView with RadioButton in singleChoice mode and a custom row layout

1) Add private int selected = -1 to CitizenAdapter.
2) Add click listener to each radiobutton:

holder.radioCitizen.setOnClickLisener(new View.OnClickListener() 
    {                              
        @Override
        public void onCheckedChanged(View view) {
            selected = (Integer) view.getTag();
            notifyDataSetChanged();
        }
    });

3) Set tag for each radiobutton to current position and set checked state:

// After you set text to 4 textviews
holder.radioButCitizen.setTag(position);
holder.radioButCitizen.setChecked(position == selected);
    int selected = 0;

@Override
public View getView(final int position, View convertView, ViewGroup parent) 
{
    // TODO Auto-generated method stub

    ViewHolder holder;
    final RadioButton motif;

    if (null == convertView) 
    {
        convertView = View
                .inflate(parent.getContext(), R.layout.motif_item, null);
        holder = new ViewHolder(convertView);
        convertView.setTag(holder);
    }

    holder = (ViewHolder) convertView.getTag();
    motif = (RadioButton) holder.getmotif();

    motif.setTag(position);

    motif.setText(motifList.get(position));

    if(position == 0)
    {
        motif.setChecked(true);
    }
    else
        motif.setChecked(false);

    motif.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            selected = position;
            notifyDataSetChanged();
        }
    });

    if(position == selected)
        motif.setChecked(true);
    else
        motif.setChecked(false);

    return convertView;
}

private class ViewHolder {

    private View mRow;
    private RadioButton motif = null;

    public ViewHolder(View row) {
        mRow = row;
    }

    public RadioButton getmotif() {
        if (motif == null) {
            motif = (RadioButton) mRow.findViewById(R.id.itemMotif);
        }
        return motif;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!