The RecyclerView-Pool-Controller is a small extension for working with viewholders. This module provides storage of previously created viewholders in the stack for further reuse.
Import this extension as a module into your project and connect it to the main project.
implementation "com.github.FedorovaA:recyclerview-pool-controller:1.0"
The module has two options for working with viewholders:
- Simple creation of viewholders in the background thread.
- Inflating view using AsyncLayoutInflater, creating viewholders in the background and further transferring the created view in constructor.
In the main activity of the application take the following steps:
class Activity : AppCompatActivity() {
// Create a delegate variable that will pass to the module
// which viewholders to use for storage in the stack
private val createVhDelegate = object : GlobalRecycledViewPoolController.CreateViewHolderDelegate {
// simple creation
override fun createViewHolderWithAsyncInflater(viewType: Int, view: View): RecyclerView.ViewHolder? {
return viewHolderDelegateWrapper.setupAsyncViewHolder(viewType, view)
}
// with AsyncLAyoutInflater
override fun createViewHolderInBackground(viewType: Int): RecyclerView.ViewHolder? {
return viewHolderDelegateWrapper.setupBgViewHolder(viewType, this@MainActivity)
}
}
private val completionCallback: () -> Unit = {}
// Initialize the controller
override fun onCreate(savedInstanceState: Bundle?) {
// simple creation
GlobalRecycledViewPoolController.initialize(List<GlobalRecycledViewPoolController.ViewHolderCacheParams>, BackgroundViewHolderInitializer(), createVhDelegate, completionCallback)
// or with AsyncLAyoutInflater
GlobalRecycledViewPoolController.initialize(List<GlobalRecycledViewPoolController.ViewHolderCacheParams>, AsyncViewHolderInitializer(this), createVhDelegate, completionCallback)
}
}
In the place where you set the adapter, add the global pool in RecyclerView
recyclerView.setRecycledViewPool(GlobalRecycledViewPool())
In the onCreateViewHolder method of the adapter.
class Adapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return GlobalRecycledViewPoolController.getViewHolderForType(viewType)
}
}
This flag shows successfully initialize
GlobalRecycledViewPoolController.isInitialized
If you need to set something to the viewholder once (i.e click listener) so you can call this method. For example, during adapter initialization.
fun setupViewHolderIfNeed(viewType: Int, callback: (RecyclerView.ViewHolder) -> Unit)
- All the viewTypes viewholder`s that you delegate to the module during initialization must be different.
- All layout parameters of the main container the viewholder (width, height and etc.) must be set during initialization. This is necessary since the parent for viewholders is null.