代码 B 是一个带有单选按钮的自定义 RecyclerView。
代码A中的fun methodA()和fun methodB()中的mCustomAdapter都发生了变化,因此其引用get () = mCustomAdapter.getSelectedIndex()也发生了变化,这意味着val属性mySelectedIndex从不同的地址获取值。
在我看来,val属性无法更改,为什么应用程序不会导致错误?
代码A
private lateinit var mCustomAdapter: CustomAdapter
private val mySelectedIndex get () = mCustomAdapter.getSelectedIndex()
private fun methodA(){
mCustomAdapter= CustomAdapter(allListA)
mRecyclerView.adapter= mCustomAdapter
backup(mySelectedIndex)
}
private fun methodB(){
mCustomAdapter= CustomAdapter(allListB)
mRecyclerView.adapter= mCustomAdapter
restore(mySelectedIndex)
}
Run Code Online (Sandbox Code Playgroud)
代码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)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
修改的
我想Code DD和Code EE可以达到同样的效果,对吗?
代码DD
var aImpl = 0
val a: Int get() = aImpl
fun seta(){
aImpl=5
}
Run Code Online (Sandbox Code Playgroud)
代码EE
var b:Int=0
fun setb(){
b=5
}
Run Code Online (Sandbox Code Playgroud)
在我看来,val属性无法更改,为什么应用程序不会导致错误?
你必须调整你的直觉。
在 Kotlin 中,val意思是“只读属性”,而不是“不可变属性”。只有没有自定义 getter 的 val 才可以被认为是不可变的。
| 归档时间: |
|
| 查看次数: |
1973 次 |
| 最近记录: |