The Code B is a customized RecyclerView.Adapter
with RadioButton
.
I hope to get the current selected index of the RadioButton
, so I add a property mySelectedIndex
in Code A, but mySelectedIndex
will not change after it's called fro the first time.
How can I do this? Thanks!
And more,
private lateinit var selectedIndex= mCustomAdapter.getSelectedIndex() will not work too!
Code A
private lateinit var mCustomAdapter: CustomAdapter
private val mySelectedIndex by lazy {
mCustomAdapter.getSelectedIndex()
}
private fun a(){
backup(mySelectedIndex)
}
private fun b(){
restore(mySelectedIndex)
}
Code B
class CustomAdapter (val backupItemList: List<MSetting>) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
val noRecord=-1
private var mSelectedIndex = 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 getSelectedIndex():Int{
return mSelectedIndex
}
fun setSelectedIndex(index:Int){
if (index in 0..(backupItemList.size-1) ){
mSelectedIndex=index
}
notifyDataSetChanged();
}
override fun onBindViewHolder(holder: CustomAdapter.ViewHolder, position: Int) {
holder.bindItems(backupItemList[position])
}
override fun getItemCount(): Int {
return backupItemList.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindItems(aMSetting: MSetting) {
itemView.radioButton.setOnClickListener {
mSelectedIndex=adapterPosition
notifyDataSetChanged();
}
if(adapterPosition == 0 && mSelectedIndex == noRecord) {
itemView.radioButton.isChecked = true
mSelectedIndex=adapterPosition
}
else {
itemView.radioButton.isChecked =(adapterPosition == mSelectedIndex)
}
}
}
}