Create a list with RecyclerView in Kotlin

Lists are the most common ways of representing collections of similar data . Thus a RecyclerView is a widget that we Android developers have to deal with very frequently . Following are the steps involved in implementing a RecyclerView . In this tutorial we shall implement the recyclerview using Kotlin.

1. Add the recyclerview dependency in the app level build.gradle
2. Create a data class to hold information of each post
3. Add RecycerView widget to the layout
4. Create the RecyclerView adapter
5. Access and set up the RecyclerView from the Activity
6. Handle click action on the list items

1. Add the recyclerview dependency in the app level build.gradle
compile ‘com.android.support:recyclerview-v7:27.0.2’

2. Create a data class to hold information of each post

	package com.droidmonk.beginkotlin.recycler_demo

	/**
	 * Created by gitudrebel on 30-11-2017.
	 */
	data class Post(val title : String, val link :String)

	fun getPostList(): ArrayList{
	    val postList=ArrayList()
	    postList.add(Post("Post 1"," First post"));
	    postList.add(Post("Post 2"," Second post"));
	    postList.add(Post("Post 3"," Third post"));
	    postList.add(Post("Post 4"," Fourth post"));

	    return postList
	}

3. We have a prety simple layout as shown below .




    

	

4. Create the RecyclerView adapter

internal class CourseListAdapter(val postList : ArrayList, val itemClickListener: (Post) -> Unit) : RecyclerView.Adapter(){
    override fun getItemCount(): Int {
        return postList.size
    }

    override fun onBindViewHolder(holder: PostsViewHolder?, position: Int) {
        if (holder != null) {
            holder.itemView.tv_title.text=postList[position].title
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): PostsViewHolder {
        val v = LayoutInflater.from(parent?.context).inflate(R.layout.each_post_view, parent, false)
        return PostsViewHolder(v)
    }

    class PostsViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView)

}

5. Access and set up the RecyclerView from the Activity

 	rv_post.layoutManager = LinearLayoutManager(this)

        val adapter = CourseListAdapter(
                getPostList()
        ) {
            Toast.makeText(this, "Hello", Toast.LENGTH_LONG).show()
        }

        rv_post.adapter=adapter

6. Handle click action on the list items

	    val adapter = CourseListAdapter(
                getPostList()
        ) {
            Toast.makeText(this, "Hello", Toast.LENGTH_LONG).show()
        }

Leave a Reply

Your email address will not be published.