Access list from inside a Viewholder in Kotlin

Asked

Viewed 179 times

0

I need to access a list that is in the Adapter, however, I need to access being in a Viewholder, I know that with Java it would be enough to reference the list, however, in Kotlin the list is not recognized, because?

class SearchFilterAdapter(private val filterList: List<Filter>) :
        RecyclerView.Adapter<SearchFilterAdapter.ViewHolder>(), FastScrollRecyclerView.SectionedAdapter {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_search_filter, parent, false)
        return ViewHolder(view)
    }

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

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(filterList[position])
    }

    override fun getSectionName(position: Int): String {
        return filterList[position].group?.toUpperCase()!!
    }

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

        val sectionTextView = itemView?.sectionTextView
        val filterCheckBox = itemView?.filterCheckBox
        val rootLayout = itemView?.rootLayout

        fun bind(filter: Filter) {

            if(filter.isFirst) {
                sectionTextView?.visibility = View.VISIBLE
                sectionTextView?.text = filter.group?.toUpperCase()
            } else {
                sectionTextView?.visibility = View.GONE
            }

            filterCheckBox?.isChecked = filter.isChecked

            filterCheckBox?.setOnCheckedChangeListener {
                buttonView, isChecked ->
                //filterList[position].isChecked = isChecked
            }

            filterCheckBox?.text = filter.category
        }
    }
}

Note that there is a comment, that’s where I tried to access the list that is on Adapter.

1 answer

2


In Kotlin, a nested class, by default, cannot access members of the class from outside.

To achieve this, use the modifier inner in the statement of nested class:

class SearchFilterAdapter(private val filterList: List<Filter>) :
        RecyclerView.Adapter<SearchFilterAdapter.ViewHolder>(), FastScrollRecyclerView.SectionedAdapter {

    ...

    inner class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
        ...
    }
}

You can read more details on documentation of nested and Inner classes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.