Home > Software engineering >  How to get `layoutInflator` in adapter class?
How to get `layoutInflator` in adapter class?

Time:01-04

I have a use case...

I want to get layoutInflator to bind different Views for nested recyclerView. Is there any best way to get layoutInflator?

I was trying to get it from onBindViewHolder

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder. //something?
}

CodePudding user response:

You shouldn't be inflating anything in onBindViewHolder - onCreateViewHolder is where you set up a ViewHolder object that displays a list item, including inflating its layout views. onBindViewHolder is where you interact with those views, to display the appropriate data for the current item.

Those created ViewHolders get reused, so instead of inflating views for every item, you just create a handful of ViewHolders that get swapped around as you scroll the list. That recycling of a pool of VHs is why it's called a RecyclerView.

Generally, you'd store references to the inflated views inside each ViewHolder, like in this example:

/**
 * Provide a reference to the type of views that you are using
 * (custom ViewHolder)
 */
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
    val textView: TextView

    init {
        // Define click listener for the ViewHolder's View
        textView = view.findViewById(R.id.textView)
    }
}

That way, the ViewHolder that gets passed into onBindViewHolder has a textView field you can access, e.g. to set its text contents to display data for the current item. (If you're using View Binding, you could store a reference to the binding object instead, and access the views through holder.binding.textView etc)

I don't know what you're doing with nested RecyclerViews, but the principle is the same - each ViewHolder in the main RV will contain another RV, with its own adapter and data set, created and initialised in onCreateViewHolder. If you want to change its contents (because you're displaying a particular item in the main RV list) you'd probably want to add a setData function on the nested RV's adapter that changes its data set and refreshes the display. Let the adapter handle inflating things when it needs to, inside onCreateViewHolder

CodePudding user response:

You can keep the reference in a ViewHolder


    class ViewHolder(view: View, val layoutInflater: LayoutInflater) : RecyclerView.ViewHolder(view) {
    }

    override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
        val layoutInflator = LayoutInflater.from(viewGroup.context)
        val view = layoutInflator
                .inflate(R.layout.text_row_item, viewGroup, false)

        return ViewHolder(view, layoutInflator)
    }

    override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {

        //viewHolder.layoutInflator
    }

  • Related