Неразрешенная ссылка: LAYOUT_INFLATER_SERVICE внутри onBindViewHolder - PullRequest
0 голосов
/ 31 декабря 2018

Внутри OnBindViewHolder моего RecyclerView Adapter, я получил несколько предметов.Один из них (ITEM_TRATAMENTOS) получил setOnClickListener, цель которого - создать LinearLayout при нажатии кнопки (add_field_btn).Проблема в том, что единственный аргумент getSystemService является неразрешенным ( Context.LAYOUT_INFLATER_SERVICE ).

В ViewPagers он работает нормально, но внутри OnBindViewHolder это не так.

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

Ожидаемый результат - создать новую строку, которая будет работать, если она находилась в обычном режиме.

Ответы [ 2 ]

0 голосов
/ 31 декабря 2018

Альтернативное решение - получить LayoutInflater от parentLinearLayout ViewGroup.

Пример

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
}

Также следует помнить о последствиях добавленияслишком много просмотров без их переработки.Возможно, вам понадобится еще один RecyclerView, если число достаточно велико.

0 голосов
/ 31 декабря 2018

Шаг # 1: Добавить параметр LayoutInflater в конструктор вашего подкласса RecyclerView.Adapter.

Шаг # 2: При создании RecyclerView.Adapter передать LayoutInflater, полученную изgetLayoutInflater() о вашей активности.

Например, вот RecyclerView.Adapter с именем ColorAdapter:

/*
  Copyright (c) 2018 CommonsWare, LLC

  Licensed under the Apache License, Version 2.0 (the "License"); you may not
  use this file except in compliance with the License. You may obtain   a copy
  of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
  by applicable law or agreed to in writing, software distributed under the
  License is distributed on an "AS IS" BASIS,   WITHOUT WARRANTIES OR CONDITIONS
  OF ANY KIND, either express or implied. See the License for the specific
  language governing permissions and limitations under the License.

  Covered in detail in the book _Elements of Android Jetpack_

  https://commonsware.com/Jetpack
*/

package com.commonsware.jetpack.sampler.recyclerview

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter

class ColorAdapter(private val inflater: LayoutInflater) :
  ListAdapter<Int, ColorViewHolder>(ColorDiffer) {

  override fun onCreateViewHolder(
    parent: ViewGroup,
    viewType: Int
  ): ColorViewHolder {
    return ColorViewHolder(inflater.inflate(R.layout.row, parent, false))
  }

  override fun onBindViewHolder(holder: ColorViewHolder, position: Int) {
    holder.bindTo(getItem(position))
  }

  private object ColorDiffer : DiffUtil.ItemCallback<Int>() {
    override fun areItemsTheSame(oldColor: Int, newColor: Int): Boolean {
      return oldColor == newColor
    }

    override fun areContentsTheSame(oldColor: Int, newColor: Int): Boolean {
      return areItemsTheSame(oldColor, newColor)
    }
  }
}

Обратите внимание, что мой конструктор ColorAdapter имеет private val inflater: LayoutInflater в качестве параметра.

Вот действие, которое использует это ColorAdapter:

/*
  Copyright (c) 2018 CommonsWare, LLC

  Licensed under the Apache License, Version 2.0 (the "License"); you may not
  use this file except in compliance with the License. You may obtain   a copy
  of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
  by applicable law or agreed to in writing, software distributed under the
  License is distributed on an "AS IS" BASIS,   WITHOUT WARRANTIES OR CONDITIONS
  OF ANY KIND, either express or implied. See the License for the specific
  language governing permissions and limitations under the License.

  Covered in detail in the book _Elements of Android Jetpack_

  https://commonsware.com/Jetpack
*/

package com.commonsware.jetpack.sampler.recyclerview

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*

class MainActivity : AppCompatActivity() {
  private val random = Random()

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    items.apply {
      layoutManager = LinearLayoutManager(this@MainActivity)
      addItemDecoration(
        DividerItemDecoration(this@MainActivity, DividerItemDecoration.HORIZONTAL)
      )
      adapter = ColorAdapter(layoutInflater).apply {
        submitList(buildItems())
      }
    }
  }

  private fun buildItems() = generateSequence { random.nextInt() }
    .take(25)
    .toList()
}

Поскольку мы с вами пишем в Kotlin, вызов getLayoutInflater() превращается в ссылку на layoutInflater собственность на деятельность.Поэтому, когда я создаю ColorAdapter, я использую ColorAdapter(layoutInflater), чтобы передать экземпляр LayoutInflater.

...