Skip to content

Instantly share code, notes, and snippets.

@joshskeen
Created April 22, 2015 03:03
Show Gist options
  • Save joshskeen/4fcd3f7ba7d37ee69fee to your computer and use it in GitHub Desktop.
Save joshskeen/4fcd3f7ba7d37ee69fee to your computer and use it in GitHub Desktop.
radio button recyclerview
abstract class RadioAdapter<T> extends RecyclerView.Adapter<RadioAdapter.ViewHolder> {
public int mSelectedItem = -1;
private Context mContext;
private List<T> mItems;
public RadioAdapter(Context context, List<T> items) {
mContext = context;
mItems = items;
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, final int i) {
viewHolder.mRadio.setChecked(i == mSelectedItem);
}
@Override
public int getItemCount() {
return mItems.size();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
final View view = LayoutInflater.from(mContext).inflate(R.layout.view_radio_item, viewGroup, false);
return new ViewHolder(view);
}
public class ViewHolder extends RecyclerView.ViewHolder {
public RadioButton mRadio;
public TextView mText;
public ViewHolder(final View inflate) {
super(inflate);
mText = (TextView) inflate.findViewById(R.id.text);
mRadio = (RadioButton) inflate.findViewById(R.id.radio);
View.OnClickListener l = v -> {
mSelectedItem = getAdapterPosition();
notifyItemRangeChanged(0, mItems.size());
};
itemView.setOnClickListener(l);
mRadio.setOnClickListener(l);
}
}
}
@lRadha
Copy link

lRadha commented Nov 5, 2016

How then you are going to get the selected item in the class using this adapter class?

@pishguy
Copy link

pishguy commented Jun 3, 2017

@mutexkid thanks

@masfahri
Copy link

Thank u

@luararamos
Copy link

Thank you so much, it helped me not to do it stupidly.

@diigel
Copy link

diigel commented Jan 21, 2020

thanks, this clean my issue

@yuaneko95
Copy link

I used the tutorial above. I have 3 radio buttons. when I checked on the 4x radio button it couldn't be checked but in the log it managed to bring up the index and text of the radio button

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment