Creating custom RecyclerView adapter

To show all the user list, we will use the RecyclerView. For our project, we need to customize the RecyclerView adapter in our own way. In this adapter, we mainly pass the user model. This will show the username, email, and contact number. Let's create an adapter named UserListAdapter.kt and extend RecyclerView.Adapter<UserListAdapter.UserViewHolder>()Here is the code for the UserListAdapter.kt:

class UserListAdapter internal constructor(context: Context) :
RecyclerView.Adapter<UserListAdapter.UserViewHolder>() {

private val mLayoutInflater: LayoutInflater = LayoutInflater.from(context)!!
private var mUsers: List<Users> = emptyList() // Cached copy of users


inner class UserViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val rowName: TextView = itemView.name
val rowEmail: TextView = itemView.email
val rowContactNumber: TextView = itemView.contactNumber
val rowAddress: TextView = itemView.contactNumber
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
val itemView: View = mLayoutInflater.inflate(R.layout.recyclerview_item, parent, false)
return UserViewHolder(itemView)
}

override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
holder.rowName.text = mUsers[position].username
holder.rowEmail.text = mUsers[position].email
holder.rowContactNumber.text = mUsers[position].contactNumber
holder.rowAddress.text = mUsers[position].address
}

override fun getItemCount(): Int {
return mUsers.size
}

internal fun setNewUser(users: List<Users>) {
mUsers = users
notifyDataSetChanged()
}
}

According to the code:

onCreateViewHolder()
onBindViewHolder()
UserViewHolder()

Here we initialize four attributes of the activity_new_user.xml in the UserViewHolder inner class :

val rowName: TextView = itemView.name
val rowEmail: TextView = itemView.email
val rowContactNumber: TextView = itemView.contactNumber
val rowAddress: TextView = itemView.contactNumber

We have set the userModel's value in these four attributes in onBindViewHolder() function as follows:

holder.rowName.text = mUsers[position].username
holder.rowEmail.text = mUsers[position].email
holder.rowContactNumber.text = mUsers[position].contactNumber
holder.rowAddress.text = mUsers[position].address
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.231.194