This recyclerview is a simplified version of the recyclerview that is often used to create lists, which only requires a few lines of code that are already prepared and can be customized.
For Example:
The first step is to create a view of the recyclerview using an xml file
Then, you can create an class of recyclerview and extend to BaseAsyncRecyclerAdapter. For example:
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import com.wahidabd.library.presentation.adapter.BaseAsyncRecyclerAdapter
import com.wahidabd.library.presentation.adapter.viewholder.BaseAsyncItemViewHolder
import com.wahidabd.onelibrary.databinding.ItemRecyclerBinding
class TestBaseAsyncRecyclerAdapter(
private val context: Context
) : BaseAsyncRecyclerAdapter<String, TestBaseAsyncRecyclerAdapter.ViewHolder>(){
override fun getViewBinding(parent: ViewGroup, viewType: Int): ViewBinding =
ItemRecyclerBinding.inflate(LayoutInflater.from(context), parent, false)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder =
ViewHolder(getViewBinding(parent, viewType))
inner class ViewHolder(binding: ViewBinding) : BaseAsyncItemViewHolder<String>(binding = binding){
override fun bind(data: String) {
with(binding as ItemRecyclerBinding){
tvTitle.text = data
}
}
}
}
Recyclerview and event listener
If you need events to handle clicks and other things, you can use lambda expressions as parameters. For example:
class TestBaseAsyncRecyclerAdapter(
private val context: Context,
private val onItemClicked: (String) -> Unit
) : BaseAsyncRecyclerAdapter<String, TestBaseAsyncRecyclerAdapter.ViewHolder>(){
override fun getViewBinding(parent: ViewGroup, viewType: Int): ViewBinding =
ItemRecyclerBinding.inflate(LayoutInflater.from(context), parent, false)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder =
ViewHolder(getViewBinding(parent, viewType))
inner class ViewHolder(binding: ViewBinding) : BaseAsyncItemViewHolder<String>(binding = binding){
override fun bind(data: String) {
with(binding as ItemRecyclerBinding){
tvTitle.text = data
tvTitle.onClick {
onItemClicked.invoke(data)
}
}
}
}
}
After the adapter is successfully created, you can call the adapter on the Activity/Fragment to enter data according to your needs, to use it you can use kotlin lazy. For example:
// Activity/Fragment
private val asyncAdapter: TestBaseAsyncRecyclerAdapter by lazy {
TestBaseAsyncRecyclerAdapter(
context = this,
onItemClicked = {}
)
}
// and insert data
override fun initObservers() {
asyncAdapter.setData = Constant.dataList()
}