What is RecyclerView?
The RecyclerView widget is a more advanced and flexible version of ListView. This widget is a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views.
Here I would demonstrate you a working example of RecyclerView, with some basic functionality. The RecyclerView we are going to design contains a list of books displaying the book Image, name, and author.
Get GITHUB code from Here.
Creating New Project
1. In Android Studio, go to File ⇒ New Project and fill all the details required to create a new project. When it prompts to select a default activity, select Blank Activity and proceed.
2. Open build.gradle and add recyclerview dependency com.android.support:recyclerview-v7:26.1.0 and rebuild the project.
Build.gradle
dependencies { // RecyclerView implementation 'com.android.support:recyclerview-v7:26.1.0' }
3. I have refracted activity_main.xml by the name activity_booklist.xml in which I have added one RecyclerView with the following basic properties.
activity_booklist.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.lenovo.recyclerview.activity.BookListActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/recycler_view" android:scrollbars="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" > </android.support.v7.widget.RecyclerView> </RelativeLayout>
Writing the Adapter Class
After adding the RecyclerView widget, let’s start writing the adapter class to render the data. The RecyclerView adapter is same as ListView but the override methods are different.
4. Create a class named Book.java and declare bookName, authorName and ImageResource(for Image). No need to set setter/getter function as it creates in its own.
Book.java
package com.example.lenovo.recyclerviewkotlin data class Book(var authorName: String,var bookName: String,var imageResource: Int)
5. Create a layout xml named book_list_row.xml with the below code. This layout file shows a single row in recycler view by displaying book name, image, and author name.
book_list_row.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="horizontal"> <ImageView android:id="@+id/img_book" android:layout_width="100dp" android:layout_height="200dp" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:orientation="vertical"> <TextView android:id="@+id/book_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAllCaps="true" android:textColor="@color/colorPrimaryDark" android:textSize="22sp" android:textStyle="bold" /> <TextView android:id="@+id/author_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18sp" android:textStyle="bold" /> </LinearLayout> </LinearLayout>
6. Now create a class named BookAdapter.java and add the below code. Here onCreateViewHolder() method inflates book_list_row.xml. In onBindViewHolder() method the appropriate book data (authorName, bookName and bookImage) set to each row.
BookAdapter.java
package com.example.lenovo.recyclerviewkotlin
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
class BookAdapter(val bookList: List<Book>) : RecyclerView.Adapter<BookAdapter.MyViewHolder>() {
class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val authorName: TextView = view.findViewById(R.id.author_name)
val bookName: TextView = view.findViewById(R.id.book_name)
val imageView: ImageView = view.findViewById(R.id.img_book)
fun bindItems(item: Book) {
authorName.setText(item.authorName)
bookName.setText(item.bookName)
imageView.setImageResource(item.imageResource)
//setting onclicklistener on each item
itemView.setOnClickListener({
Toast.makeText(itemView.context, item.bookName + " " + " book is Clicked", Toast.LENGTH_SHORT).show()
})
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.book_list_row, parent, false)
return MyViewHolder(view)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bindItems(bookList.get(position));
}
override fun getItemCount(): Int {
return bookList.size
}
}
7. Open drawable folder under res directory and paste all the book photos which you have copied from somewhere else.
8. Now open BookListActivity.java refracted form of MainActivity.java and do the below changes. Here prepareMovieData() method adds sample data to list view.
BookListActivity.java
package com.example.lenovo.recyclerviewkotlin import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import java.util.ArrayList class BookListActivity : AppCompatActivity() { private var recyclerView: RecyclerView? = null private val bookList = ArrayList<Book>() private val mAdapter: BookAdapter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.booklist) val recyclerView: RecyclerView = findViewById(R.id.recycler_view) prepareBookData() //vertical RecyclerView recyclerView!!.layoutManager = LinearLayoutManager(applicationContext) //provides basic animations on remove, add, and move events that happen to the items in a RecyclerView. //RecyclerView uses a DefaultItemAnimator by default. recyclerView!!.itemAnimator = DefaultItemAnimator() val adapter = BookAdapter(bookList) //now adding the adapter to recyclerview recyclerView!!.adapter = adapter } //preparing bookList data private fun prepareBookData() { var book = Book("Munshi Premchand", "Nirmala", R.drawable.nirmala) bookList.add(book) book = Book("Harivansh Rai Bachchan", "Madhushala", R.drawable.madhushala2) bookList.add(book) book = Book("Ramdhari Singh Dinkar", "Rashmirathi", R.drawable.rashmirathi) bookList.add(book) book = Book("Dharamvir Bharti", "Gunahon Ka Devta", R.drawable.gunahokedevta2) bookList.add(book) book = Book("Munshi Premchand", "Shatranj Ke Khiladi", R.drawable.shatranj2) bookList.add(book) book = Book("Bhisham Sahni", "Tamas", R.drawable.tamas) bookList.add(book) book = Book("Dharamvir Bharti", "Suraj Ka Satva Ghoda", R.drawable.suraj) bookList.add(book) book = Book("Munshi Premchand", "Karmabhumi", R.drawable.karmabhumi) bookList.add(book) book = Book("Kashinath Singh", "Kassi Ka Assi", R.drawable.kashi_ka_assi) bookList.add(book) book = Book("Bhagwati Charan Verma", "Chitralekha", R.drawable.chitralekha) bookList.add(book) } }
Now if you run the app you can see the book list will look like this:
Adding RecyclerView Divider/Separator
9.You can add the divider line between rows by using DividerItemDecoration provided by the support library. Add item decoration on RecyclerView as shown below.
// adding inbuilt divider line recyclerView!!.addItemDecoration(DividerItemDecoration(this, LinearLayoutManager.VERTICAL)) val adapter = BookAdapter(bookList) //now adding the adapter to recyclerview recyclerView!!.adapter = adapter
Now if you run the app, you should see a divider line separating each row.
Displaying Horizontal Scrolling RecyclerView
10. If you want to display the RecyclerView in Horizontal manner, you can do that just by changing a single line of code. All you have to do is provide direction to layout manager i.e LinearLayoutManager.HORIZONTAL as shown below.
//horizontal RecyclerView
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.HORIZONTAL,false));
Final Code
Below is the complete code of BookListActivity.java
BookListActivity.java
package com.example.lenovo.recyclerviewkotlin import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import java.util.ArrayList class BookListActivity : AppCompatActivity() { private var recyclerView: RecyclerView? = null private val bookList = ArrayList<Book>() private val mAdapter: BookAdapter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.booklist) val recyclerView: RecyclerView = findViewById(R.id.recycler_view) prepareBookData() //vertical RecyclerView recyclerView!!.layoutManager = LinearLayoutManager(applicationContext) //horizontal RecyclerView recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.HORIZONTAL,false)); //provides basic animations on remove, add, and move events that happen to the items in a RecyclerView. //RecyclerView uses a DefaultItemAnimator by default. recyclerView!!.itemAnimator = DefaultItemAnimator() // adding inbuilt divider line recyclerView!!.addItemDecoration(DividerItemDecoration(this, LinearLayoutManager.VERTICAL)) val adapter = BookAdapter(bookList) //now adding the adapter to recyclerview recyclerView!!.adapter = adapter } //preparing bookList data private fun prepareBookData() { var book = Book("Munshi Premchand", "Nirmala", R.drawable.nirmala) bookList.add(book) book = Book("Harivansh Rai Bachchan", "Madhushala", R.drawable.madhushala2) bookList.add(book) book = Book("Ramdhari Singh Dinkar", "Rashmirathi", R.drawable.rashmirathi) bookList.add(book) book = Book("Dharamvir Bharti", "Gunahon Ka Devta", R.drawable.gunahokedevta2) bookList.add(book) book = Book("Munshi Premchand", "Shatranj Ke Khiladi", R.drawable.shatranj2) bookList.add(book) book = Book("Bhisham Sahni", "Tamas", R.drawable.tamas) bookList.add(book) book = Book("Dharamvir Bharti", "Suraj Ka Satva Ghoda", R.drawable.suraj) bookList.add(book) book = Book("Munshi Premchand", "Karmabhumi", R.drawable.karmabhumi) bookList.add(book) book = Book("Kashinath Singh", "Kassi Ka Assi", R.drawable.kashi_ka_assi) bookList.add(book) book = Book("Bhagwati Charan Verma", "Chitralekha", R.drawable.chitralekha) bookList.add(book) } }
Now when you run the app, it will look like this.