Creating the adapter for posts

Let's create a custom RecycleView adapter named PostRecycleViewAdapter.kt to display the post list. We have shown you how to create custom adapters in Chapter 4, Spring Modules for Android, so we won't repeat it. Here is the PostRecycleViewAdapter class:

class PostRecycleViewAdapter(private var context: Context,
private val postList: List<Post>):
RecyclerView.Adapter<PostRecycleViewAdapter.ViewHolder>() {
-----
-----
}

Now create the ViewHolder class and initialize all the content of the post_item layout in PostRecycleViewAdapter.kt, as shown in the following code:

class ViewHolder(view: View): RecyclerView.ViewHolder(view){
val postRoot = view.findViewById(R.id.postRoot) as ConstraintLayout

val profileFullName = view.findViewById(R.id.profileFullNamePost) as TextView
val username = view.findViewById(R.id.usernamePost) as TextView
val postedDate = view.findViewById(R.id.postedDate) as TextView
val postText = view.findViewById(R.id.postText) as TextView
}

Now override onCreateViewHolder() and return the ViewHolder class:

override fun onCreateViewHolder(viewGroup: ViewGroup, p1: Int): ViewHolder {
val layoutInflater = LayoutInflater.from(context).inflate(R.layout.post_item, viewGroup, false)
return ViewHolder(layoutInflater)
}

Now, we need to set the value in every raw of the list based on its position. To do this, override the onBindViewHolder() function and add this code:

override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {

val userDetails = postList[position]

viewHolder.profileFullName.text = "${userDetails.profile!!.firstName} ${userDetails.profile!!.lastName} "
viewHolder.username.text = userDetails.profile!!.username
viewHolder.postedDate.text = userDetails.postCreatedTime
viewHolder.postText.text = userDetails.text

}
..................Content has been hidden....................

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