Search code examples
androidkotlincustom-adapter

Why can't I use the var mSelectedItem in inner class ViewHolder?


I define mSelectedItem as a public var in the class CustomAdapter, I think mSelectedItem=getAdapterPosition() will be Ok when I use mSelectedItem in inner class ViewHolder.

But it failed, and display "Unresolved reference: mSelectedItem" error, why?

And more, what is good way for getAdapterPosition() in Kotlin, there is hint which display "This inspection reports calls to java get and set methods that can be replaced with use of Kotlin synthetic properties", but it will cause errro when I use mSelectedItem=getAdapterPosition .

class CustomAdapter (val backupItemList: List<MSetting>) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {

    public var mSelectedItem = -1


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


    override fun onBindViewHolder(holder: CustomAdapter.ViewHolder, position: Int) {
        holder.bindItems(backupItemList[position])
        holder.itemView.radioButton.setChecked(position == mSelectedItem);
    }


    override fun getItemCount(): Int {
        return backupItemList.size
    }


    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun bindItems(aMSetting: MSetting) {               

            itemView.radioButton.tag=aMSetting._id
            itemView.textViewUsername.text=aMSetting.createdDate.toString()
            itemView.textViewAddress.text=aMSetting.description
            mSelectedItem=getAdapterPosition()  //It will cause error
        }
    }
}

Solution

  • If you don't want to make the ViewHolder an inner class (which you should not), you could create a class like AdapterSelection that has a field var selectedItem:Int inside it and replace your public var mSelectedItem = -1 with private var mSelectedItem = AdapterSelection(-1). Then pass the mSelectedItem to the bind method (bindItems(aMSetting: MSetting, adapterSelection:AdapterSelection) and inside the bind, set the position adapterSelection.selectedItem = getAdapterPosition().

    You could have passed the adapter itself, but it is messy, that's why I suggest making another class.