RecyclerViewPresenter

Additional

Language
Kotlin
Version
1.5.2 (Dec 25, 2016)
Created
May 15, 2016
Updated
May 7, 2021
Owner
Jan Rabe (kibotu)
Contributor
Jan Rabe (kibotu)
1
Activity
Badge
Generate
Download
Source code
APK file

Promotion

RecyclerView Presenter

Convenience library to handle different view types with different presenters in a single RecyclerView.

How to install

repositories {
    maven {
 url "https://jitpack.io"
    }
}

dependencies {
    implementation 'com.github.kibotu:RecyclerViewPresenter:-SNAPSHOT'
}

How to use

  1. Create a presenter, e.g. PhotoPresenter or LabelPresenter
class LabelPresenter : Presenter<String>(R.layout.label_presenter_item) {

    private val View.label: TextView
        get() = findViewById(R.id.label)

    override fun bindViewHolder(viewHolder: RecyclerView.ViewHolder, item: PresenterViewModel<String>, payloads: MutableList<Any>?) = with(viewHolder.itemView) {
        logv { "bindViewHolder ${viewHolder.adapterPosition} $item payload=$payloads" }
        label.text = "${item.model}"
    }
}
  1. Add the PresenterAdapter to your RecyclerView
val adapter = PresenterAdapter()
list.adapter = adapter
  1. Register Presenter
adapter.registerPresenter(PhotoPresenter())
adapter.registerPresenter(LabelPresenter())
adapter.registerPresenter(NumberPresenter())
  1. Submit list of models with presenter matching layout to the adapter, e.g.:
val items = mutableListOf<PresenterViewModel<*>>()

for (i in 0..99) {
    items.add(PresenterModel(createRandomImageUrl(), R.layout.photo_presenter_item))
    items.add(PresenterModel(createRandomImageUrl(), R.layout.label_presenter_item))
    items.add(PresenterModel(createRandomImageUrl(), R.layout.number_presenter_item))
}

adapter.submitList(items)

5.1 Add click listener to adapter

adapter.onItemClick { item, view, position ->
    snack("$position. ${item.model}")
}

5.2 or pass to your RecyclerViewModel

val item = PresenterViewModel(createRandomImageUrl(), R.layout.photo_presenter_item) { item, view, position -> 
 snack("$position. $item")
})

Updating item

adapter.submitList(newItems)

Circular

adapter.isCircular = true

// Note: use adapter scroll methods for correct scroll position when using circular
adapter.smoothScrollToPosition(0)
adapter.scrollToPosition(0)

Notes

Follow me on Twitter:

Let me know what you think: jan.rabe@kibotu.net

Contributions welcome!

License

Copyright 2021 Jan Rabe

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.