RecyclerView Day 1: List of Friends

Have friends? RecyclerView to the rescue!

RecyclerView Day 1: List of Friends

Let's create a RecyclerView that will display a list of your friends. In this app, we will be able to scroll through a list of all of your friends. In this tutorial, we'll use Kotlin and Android Studio 3.3.2 (although any version of Android Studio will work).

New to Android Studio or Kotlin? Check out my beginner's course.

Create Project

First, we need to create a new Android Studio project. Make sure to enable Kotlin support in the setup dialog wizard. When you press Finish, Android Studio takes you to the default editor, with two open tabs: MainActivity.kt and content_main.xml. If you open MainActivity.kt, you should see the following code.

package com.example.listoffriends

import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity;
import android.view.Menu
import android.view.MenuItem

import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

        fab.setOnClickListener { view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        return when (item.itemId) {
            R.id.action_settings -> true
            else -> super.onOptionsItemSelected(item)
        }
    }
}

This class contains unnecessary code. Let's modify MainActivity.kt to the following.

package com.example.listoffriends

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)
    }
}

Create the Data Model Class

Next, we need to create a class that will contains our friend's information. To create a new Kotlin class open the Project pane on the left side of Android Studio. Make sure that the Project pane indicates that the "Android" drop-down is selected. Then open app, java, then the first folder inside of java. Right click on the com.example.listooffriends (or whatever package you gave it when you created the project) and select New, Kotlin File/Class.

Android Studio then creates the following file. Give it a name of Friend and select Class from the drop-down that appears just below the name. The file is created and should look like this:

package com.example.listoffriends

class Friend {
}

No we need to convert this into a data class. To do this, modify the file to the following.

package com.example.listoffriends

data class Friend()
A data class is a Kotlin-specific feature and is not available in Java.

We now need to add some fields to this Kotlin data class. Add a firstName, lastName and age, as follows.

package com.example.listoffriends

data class Friend(
    val firstName: String,
    val lastName: String,
    val age: Int
)

List of Friends

Back in MainActivity.kt, add the following code to the bottom of the onCreate method.

        val friends = mutableListOf<Friend>()
        for (i in 1..100) {
            friends.add(Friend("Daniel", "Malone", 25))
        }

Our Adapter will handle the displaying of our friends. Create a new Kotlin class named FriendsAdapter.

package com.example.listoffriends

class FriendsAdapter {
}

This needs to extend RecyclerView.Adapter and end with FriendsAdapter.ViewHolder.

package com.example.listoffriends

import androidx.recyclerview.widget.RecyclerView

class FriendsAdapter : RecyclerView.Adapter<FriendsAdapter.ViewHolder>() {
}
package com.example.listoffriends

import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView

class FriendsAdapter : RecyclerView.Adapter<FriendsAdapter.ViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FriendsAdapter.ViewHolder {
    }

    override fun getItemCount(): Int {
    }

    override fun onBindViewHolder(holder: FriendsAdapter.ViewHolder, position: Int) {
    }
}

This class needs to receive the list of friends from MainActivity.kt. Modify the constructor to add the friends list.

class FriendsAdapter(val friends: List<Friend>) : RecyclerView.Adapter<FriendsAdapter.ViewHolder>() {

The first we'll update is getItemCount(), because it's easy. Add friends.size.

    override fun getItemCount() = friends.size

Next, let's work on onCreateViewHolder, where we need to setup our view. This should give you an error; we'll fix it later.

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FriendsAdapter.ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.friend_row, parent, false)
        return ViewHolder(view)
    }

Next, let's create our friend_row.xml layout file. When creating the file, set Root Element to ConstraintLayout.

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/firstName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

In the above code, we setup our firstName TextView widget, and constrain it to the top and left.

RecyclerView Day 2: List of Emails

More Tutorials

Kotlin Challenge #1

Build a simple contacts manager.

Android Basic Alert Dialog Box
Basic CardView

Basic CardView

Material Design.

Rounded Corners with a Border
Rounded Button in Android Studio

Rounded Button in Android Studio

Create beautiful buttons in XML.

RecyclerView Day 3: Invoicing app

RecyclerView Day 3: Invoicing app

Built with Android Studio and Kotlin.

Build a Ridesharing Android App - Part 1

Build a Ridesharing Android App - Part 1

Getting started is sometimes the hardest part.

setOnClickListener

Add a click listener in Kotlin.

Android Login Layout

Let users sign in.