首页 > 解决方案 > 如何定义返回 Kotlin 中 RadioButton 的当前值的属性?

问题描述

代码 B 是定制RecyclerView.AdapterRadioButton

我希望得到当前选择的索引,所以我在代码A中RadioButton添加了一个属性,但在第一次调用后不会改变。mySelectedIndexmySelectedIndex

我怎样才能做到这一点?谢谢!

和更多,

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)
            }
        }

    }

}

标签: androidkotlin

解决方案


通过在by lazy此处使用委托,您可以确保在第一次初始化mySelectedIndex.

您可能想省略委托,而改为执行以下操作:

private val mySelectedIndex
    get () = mCustomAdapter.getSelectedIndex()

附带说明一下,上面的这段代码不等于以下代码:

private val mySelectedIndex
    get () = {
        mCustomAdapter.getSelectedIndex()
    }

后者将返回一个函数引用,getSelectedIndex()而前者将返回其结果。


推荐阅读