android - 如何定义返回 Kotlin 中 RadioButton 的当前值的属性?
问题描述
代码 B 是定制RecyclerView.Adapter
的RadioButton
。
我希望得到当前选择的索引,所以我在代码A中RadioButton
添加了一个属性,但在第一次调用后不会改变。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)
}
}
}
}
解决方案
通过在by lazy
此处使用委托,您可以确保在第一次初始化mySelectedIndex
.
您可能想省略委托,而改为执行以下操作:
private val mySelectedIndex
get () = mCustomAdapter.getSelectedIndex()
附带说明一下,上面的这段代码不等于以下代码:
private val mySelectedIndex
get () = {
mCustomAdapter.getSelectedIndex()
}
后者将返回一个函数引用,getSelectedIndex()
而前者将返回其结果。
推荐阅读
- sql - 用逗号分隔的页面返回不同的文件名?
- search - Vim 在搜索没有插件的文件时显示“...”并锁定
- visual-studio - 使用 Visual Studio 2019 创建 UWP PWA 应用
- shiny - 情节动画在闪亮的应用程序中不起作用?
- excel - VBA 字符串字符 Excel
- javascript - 管理 Web 浏览器本地存储数据的最有效方法
- excel - Excel VBA用户表单文本框具有使用不同文本框的动态脚本
- python - 如何在python中为棕色定义HSV renge?
- python - 如何使用来自另一个较小 DataFrame 的行索引显示或获取来自较大 DataFrame 的行数据/值?
- excel - 打开 Excel 表作为 DAO 记录集以进行追加