Search code examples
androidkotlinadapterlayout-inflater

Unresolved reference: LAYOUT_INFLATER_SERVICE inside onBindViewHolder


Inside OnBindViewHolder of my RecyclerView Adapter, I got multiple items. One of those (ITEM_TRATAMENTOS) got a setOnClickListener which has the purpose of create an LinearLayout when I click in an button (add_field_btn). The problem is that the only argument of getSystemService is unresolved (Context.LAYOUT_INFLATER_SERVICE).

In ViewPagers it works fine, but inside OnBindViewHolder, it's not the case.

 ITEM_TRATAMENTOS ->{
      val viewHolderTratamentos = holder as ViewHolderItemTratamentos
      holder.add_field_btn.setOnClickListener {
                    inflater = Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
                    val rowView = inflater.inflate(R.layout.used_products_field, null)
                    // Add the new row.
                    parentLinearLayout?.addView(rowView, parentLinearLayout?.childCount!! - 1)
            }
  }

The expected result is to create the new line, which it works if it was on an normal activity.


Solution

  • An alternative solution is to get the LayoutInflater from parentLinearLayout ViewGroup.

    Example

    parentLinearLayout?.apply { 
        val inflater = LayoutInflater.from(context) // context is now available in the receiver scope
        val rowView = inflater.inflate(R.layout.used_products_field, this, false)
        addView(rowView) // Add the view to the last position
    }
    

    Also, be aware of the consequences of adding too many views without recycling them. Probably you'd need another RecyclerView if the number is big enough.