As you know, if we want to implement multiple types in RecyclerView
I kind of use the first one.
I use a companion object to declare the static fields, which I use in my implementation.
This project was written in kotlin, but here is how I implemented an Adapter:
/**
* Created by Geert Berkers.
*/
class CustomAdapter(
private val objects: List,
) : RecyclerView.Adapter() {
companion object {
const val FIRST_CELL = 0
const val SECOND_CELL = 1
const val THIRD_CELL = 2
const val OTHER_CELL = 3
const val FirstCellLayout = R.layout.first_cell
const val SecondCellLayout = R.layout.second_cell
const val ThirdCellLayout = R.layout.third_cell
const val OtherCellLayout = R.layout.other_cell
}
override fun getItemCount(): Int = 4
override fun getItemViewType(position: Int): Int = when (position) {
objects[0] -> FIRST_CELL
objects[1] -> SECOND_CELL
objects[2] -> THIRD_CELL
else -> OTHER_CELL
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): RecyclerView.ViewHolder {
when (viewType) {
FIRST_CELL -> {
val view = inflateLayoutView(FirstCellLayout, parent)
return FirstCellViewHolder(view)
}
SECOND_CELL -> {
val view = inflateLayoutView(SecondCellLayout, parent)
return SecondCellViewHolder(view)
}
THIRD_CELL -> {
val view = inflateLayoutView(ThirdCellLayout, parent)
return ThirdCellViewHolder(view)
}
else -> {
val view = inflateLayoutView(OtherCellLayout, parent)
return OtherCellViewHolder(view)
}
}
}
fun inflateLayoutView(viewResourceId: Int, parent: ViewGroup?, attachToRoot: Boolean = false): View =
LayoutInflater.from(parent?.context).inflate(viewResourceId, parent, attachToRoot)
override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
val itemViewTpe = getItemViewType(position)
when (itemViewTpe) {
FIRST_CELL -> {
val firstCellViewHolder = holder as FirstCellViewHolder
firstCellViewHolder.bindObject(objects[position])
}
SECOND_CELL -> {
val secondCellViewHolder = holder as SecondCellViewHolder
secondCellViewHolder.bindObject(objects[position])
}
THIRD_CELL -> {
val thirdCellViewHolder = holder as ThirdCellViewHolder
thirdCellViewHolder.bindObject(objects[position])
}
OTHER_CELL -> {
// Do nothing. This only displays a view
}
}
}
}
And here is an example of a ViewHolder:
class FirstCellViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bindMedication(object: Object) = with(object) {
itemView.setOnClickListener {
openObject(object)
}
}
private fun openObject(object: Object) {
val context = App.instance
val intent = DisplayObjectActivity.intent(context, object)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(intent)
}
}