简体   繁体   中英

Single Radio Button click in Android Recyclerview

I am using Recycler View Containing list of items with radio buttons.. selecting radio button in list is possible when list size is greater then One. my main problem is with list item is one .. the radio button is not at all working fine please help me to solve this ....

this is my code

            RadioButton checked_rb = (RadioButton) v;
            if (lastCheckedRB != null) {
                lastCheckedRB.setChecked(false );

            }
            lastCheckedRB=checked_rb;

try this

public class RadioButtonAdapter extends RecyclerView.Adapter<RadioButtonAdapter.ViewHolder> {

private static final String TAG = RadioButtonAdapter.class.getSimpleName();
private List<String> tags;
private TagClickCallBack mTagClickCallBack;
private int lastCheckedPosition = -1;

public RadioButtonAdapter(TagClickCallBack tagClickCallBack) {
    tags = new ArrayList<>();
    this.mTagClickCallBack = tagClickCallBack;
}

public void addTags(List<String> newTags) {
    tags.addAll(newTags);
    notifyDataSetChanged();
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View mView = LayoutInflater.from(parent.getContext()).inflate(R.layout.radiobtn_adapter, parent, false);
    return new ViewHolder(mView);
}

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
    holder.rdoBtnProfession.setText(tags.get(position));
    holder.rdoBtnProfession.setChecked(position == lastCheckedPosition);
}

@Override
public int getItemCount() {
    return tags == null ? 0 : tags.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    @Bind(R.id.rdoBtnProfession)
    public AppCompatCheckBox rdoBtnProfession;

    public ViewHolder(View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);
        rdoBtnProfession.setOnClickListener(v -> {
            lastCheckedPosition = getAdapterPosition();
            notifyItemRangeChanged(0, tags.size());
            mTagClickCallBack.onTagClicked(tags.get(getAdapterPosition()));
        });
    }
}

You can create your custom view by setting modes like single/multi selection flags.

how to set choice mode single for listview with images

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM