代码B是带有RecyclerView.Adapter
的自定义RadioButton
。
我希望得到RadioButton
的当前所选索引,因此我在代码A中添加了一个属性mySelectedIndex
,但mySelectedIndex
在调用之后不会更改第一次。
我该怎么做?谢谢!
还有更多,
private lateinit var selectedIndex= mCustomAdapter.getSelectedIndex() will not work too!
代码A
private lateinit var mCustomAdapter: CustomAdapter
private val mySelectedIndex by lazy {
mCustomAdapter.getSelectedIndex()
}
private fun a(){
backup(mySelectedIndex)
}
private fun b(){
restore(mySelectedIndex)
}
代码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)
}
}
}
}
答案 0 :(得分:1)
在此处使用mySelectedIndex
委派,您确保在private val mySelectedIndex
get () = mCustomAdapter.getSelectedIndex()
首次初始化后返回相同的值。
您可能希望省略委派并执行类似的操作:
private val mySelectedIndex
get () = {
mCustomAdapter.getSelectedIndex()
}
作为旁注,上面的代码段不等于以下内容:
getSelectedIndex()
后者将返回Add-TextBox
的函数引用,而前者将返回其结果。
答案 1 :(得分:0)
替换
Balance
与
.value
或
private val mySelectedIndex by lazy {
mCustomAdapter.getSelectedIndex()
}
应该有用。