Skip to main content

Lists and Grids in Android with RecyclerView Kotlin Tutorial

RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It has been created to make possible construction of any lists with XML layouts as an item that can be customized vastly while improving on the efficiency of ListViews and GridViews.

Getting Started

To implement a basic RecyclerView Two sub-parts are needed to be constructed which offer the users the degree of control they require in making varying designs of their choice.

1.The ViewHolder: The ViewHolder is a java class that stores the reference to the card layout views that have to be dynamically modified during the execution of the program by a list of data obtained either by online databases or added in some other way.

2.The Data Class: The Data class is a custom java class that acts as a structure for holding the information for every item of the RecyclerView.

Implementation of the RecyclerView:

In the activity_main.xml file in layout directory, add the RecyclerView widget.


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    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=".MainActivity">


    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycleView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Create a custom layout list_item.xml file with following code.
list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    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="wrap_content">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="36dp"
        android:layout_height="36dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/ic_android" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:layout_marginTop="24dp"
        android:text="TextView"
        android:textColor="#000000"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toEndOf="@+id/imageView"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Create a ListData.java class with the following code. This class is used as (POJO) class which sets the properties of the items.
ListData.kt

data class ListData( var name :String, var imageid: Int)

Create a MyListAdapter.java class and add the following code. This class extends RecyclerView.Adapter class and override its unimplemented methods. The onCreateViewHolder() methods inflates the list_item.xml. In the onBindViewHolder() method each data items are set to each row.
MyListAdapter.kt

class MyListAdapter (private val dataSet: Array<ListData>) : RecyclerView.Adapter<MyListAdapter.ViewHolder>() {

    /**
     * Provide a reference to the type of views that you are using
     * (custom ViewHolder).
     */
    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val textView: TextView
        val imageView : ImageView

        init {

            textView = view.findViewById(R.id.textView)
            imageView = view.findViewById(R.id.imageView)

        }


    }

    // Create new views (invoked by the layout manager)
    override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
        // Create a new view, which defines the UI of the list item
        val view = LayoutInflater.from(viewGroup.context)
            .inflate(R.layout.list_item, viewGroup, false)

        return ViewHolder(view)
    }

    // Replace the contents of a view (invoked by the layout manager)
    override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {

        // Get element from your dataset at this position and replace the
        // contents of the view with that element
        viewHolder.textView.text = dataSet[position].name
        viewHolder.imageView.setImageResource(dataSet[position].imageid)
        // Define click listener for the ViewHolder's View.
        viewHolder.itemView.setOnClickListener {
            Toast.makeText(it.context,"click on item: "+dataSet[position].name,Toast.LENGTH_LONG).show();
        }
    }

    // Return the size of your dataset (invoked by the layout manager)
    override fun getItemCount() = dataSet.size
}

Finally, in the MainActivity.java class, add the following code. This class creates the array of items for MyListData class and set the adapter class to RecyclerView.
MainActivity.kt

package com.examlpe.recycleviewsample

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //create static data set
        val myListData: Array<ListData> = arrayOf<ListData>(
                ListData("Android", R.drawable.ic_android),
                ListData("Account", R.drawable.ic_baseline_account),
                ListData("Archive", R.drawable.ic_baseline_archive),
                ListData("Brightness High",R.drawable.ic_baseline_brightness_high),
                ListData("Direction Bus", R.drawable.ic_baseline_directions_bus),
                ListData("Watch", R.drawable.ic_baseline_watch),
                ListData("Wash", R.drawable.ic_baseline_wash_24),
                ListData("Tag Face", R.drawable.ic_baseline_tag_faces),
                ListData("Surfing", R.drawable.ic_baseline_surfing),
                ListData("Sports Tennis", R.drawable.ic_baseline_sports_tennis),
                ListData("Wrong Location", R.drawable.ic_baseline_wrong_location),
                ListData("Sports Kabaddi", R.drawable.ic_baseline_sports_kabaddi),
                ListData("Tag Face", R.drawable.ic_baseline_tag_faces),
                ListData("Surfing", R.drawable.ic_baseline_surfing),
                ListData("Sports Tennis", R.drawable.ic_baseline_sports_tennis),
                ListData("Wrong Location", R.drawable.ic_baseline_wrong_location),
                ListData("Sports Kabaddi", R.drawable.ic_baseline_sports_kabaddi))



        val recyclerView: RecyclerView = findViewById(R.id.recycleView)
        recyclerView.setHasFixedSize(true)
        //Listview
        recyclerView.layoutManager = LinearLayoutManager(this)
//        For gridview uncomment bellow line
//        recyclerView.layoutManager = GridLayoutManager(this,2)
        val myListAdapter = MyListAdapter(myListData)
        recyclerView.adapter = myListAdapter;


    }
}

For GirdView replace layout manager to 
 recyclerView.layoutManager = GridLayoutManager(this,2)

Result:



Comments

Post a Comment

Popular posts from this blog

Android EditText with Examples in Kotlin

In Android, EditText is a standard entry widget. A user interface element for entering and modifying text. When you define an edit text widget, you must specify the R.styleable.TextView_inputType attribute. For example, for plain text input set inputType to " text ", In case if EditText field is for password, then we need to specify the inputType as “ textPassword ”. <EditText android:id= "@+id/plain_text_input" android:layout_height= "wrap_content" android:layout_width= "match_parent" android:inputType= "text" /> See the Text Fields guide for examples of other R.styleable.TextView_inputType settings. Text Fields in Android Studio are basically EditText and we drag and drop or we can create edittext.  First, we will check the drag and drop option here EditText instance by declaring it inside a layout XML file <EditText android:id= "@+id/plain_text_input" android:layout_height= &

Android Spinner using Kotlin

 In this example, we’ll be implementing Material Spinners in our Android Application using Kotlin. Android Spinner is used to create a drop-down list on the screen. What is Android Spinner? Spinners provide a quick way to select one value from a list. In the default state, a spinner shows its currently selected value. Touching the spinner displays a dropdown menu with all other available values, from which the user can select a new one. You can add a spinner to your layout with the  Spinner  object. You should usually do so in your XML layout with a  <Spinner>  element. For example: <Spinner     android:id = "@+id/planets_spinner"     android:layout_width = "match_parent"     android:layout_height = "wrap_content" /> Spinner Callback Events  AdapterView.onItemSelectedListener interface is used to trigger the Spinner click event callbacks.  It consists of two methods:   1.onItemSelected   2.onNothingSelected XML Layout Code The code for the act