Шаг # 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
.