I desgin a radio button for each item in RecyclerView with Code B , I hope to click a normal button to check a radio button in RecyclerView which _id of MSetting is equal to a given value.
So I write some code in Code A, but I don't know how to write next step, could you help me ?
In general, I need to check a radio button inside RecyclerView programmatically.
You can't do it by RadioGroup: How to check programmatically. All radio buttons inside RecyclerView have the same ID.
RadioButton b = (RadioButton) findViewById(R.id.option1);
b.setChecked(true);
To Faysal Ahmed
Why need I to do it?
There are a Search button and a edittext control in my APP, I input a id value in edittext control,then I click Search button, the record will be found and the radio button in RecyclerView will be checked automatically!
Code A
fun SetRadioChecked(id:Long){
for (i in 0..(backupItemList.size-1)){
if (backupItemList[i]._id==id){
//Set the radio button as checked
}
}
}
Code B
class CustomAdapter (val backupItemList: List<MSetting>) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
val noRecord=-1
private var mSelectedItem = noRecord
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomAdapter.ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.item_recyclerview, parent, false)
return ViewHolder(v)
}
fun getSelectedItem():Int{
return mSelectedItem
}
override fun onBindViewHolder(holder: CustomAdapter.ViewHolder, position: Int) {
holder.bindItems(backupItemList[position])
}
fun SetRadioChecked(id:Long){
for (i in 0..(backupItemList.size-1)){
if (backupItemList[i]._id==id){
//Set the radio button as checked
}
}
}
override fun getItemCount(): Int {
return backupItemList.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindItems(aMSetting: MSetting) {
itemView.tvSubject.text=aMSetting.name
itemView.tvCreatedDate.text=aMSetting.createdDate.toDateString()
itemView.tvDescription.text=aMSetting.description
itemView.radioButton.setOnClickListener {
mSelectedItem=adapterPosition
notifyDataSetChanged();
}
if(adapterPosition == 0 && mSelectedItem == noRecord) {
itemView.radioButton.isChecked = true
mSelectedItem=adapterPosition
}
else {
itemView.radioButton.isChecked =(adapterPosition == mSelectedItem)
}
}
}
}