In the past, there were a number of ways to display data to a user. However, now it is strongly recommended to use a RecyclerView for display lists of data. Lists can be vertical or horizontal, and can be styled according to a design spec. Rows can even have different layouts depending upon the data to be displayed.
For example, a Facebook Newsfeed-style design might display an ad every five rows, or every 3 rows, or exactly on the 32rd row, however you see fit. In this tutorial, let’s create a basic RecyclerView that displays a list of users.
Step 1: Start a new Android Studio project
Setup an Android Studio project by following the steps in Android Studio Tutorial with Kotlin (2018 Edition) – Part 1, and be sure to select Basic Activity when you are prompted to Add an Activity to Mobile.
After selecting Basic Activity, continue the screens until you reach the Configure Activity screen. The defaults are fine.
Step 2: Add a RecyclerView tag to the layout
Now our project is all set up. Let’s start creating the RecyclerView. First, if it’s not already open, open content_main.xml. Then click Text near the bottom of your screen.
Then let’s replace the lone <TextView> with <RecyclerView…
The TextView tag is for displaying a single text message. We need to change this to a RecyclerView. There are only a few lines to change, which should now look like the following.
The 0dp for the layout_width and layout_height is part of ConstraintLayout. It means that the element will take up the entire space, because of the four constraints on the tag (bottom, left, right, top).
We can now close content_main.xml because we’re done making all modifications to the file.
Step 3: Create the design for the row
Next, let’s create the design for each row. This row will be repeated 100 times for a list of 100 users. There is no need to create a separate row for each user. We can user one row and the RecyclerView’s Adapter will transform the data into each layout, recycling each one as you swipe up or down.
Right click on the layout folder and select Layout resource file.
Next, name the folder row_user and click OK.
Android Studio should now look similar to this.
Next, we need to style the file row_user.xml. Open row_user.xml in Android Studio. Then select the Text tab near the bottom of your screen.
Next, add a TextView to the row_user.xml file. It should look like the following.
Step 4: Create the Adapter
Next, we need to write some Kotlin code. Right click the package containing MainActivity and create a new Kotlin class.
After creating the new file UsersAdapter (as a class), you should see a nearly-empty file titled UsersAdapter.kt.
Next, type the following.
You should notice an error in Android Studio, identified by a red line under class UsersAdapter and red text ViewHolder. Click on ViewHolder and press Alt+Enter key on Windows (or Option+Enter key on Mac). Then select Create class ‘ViewHolder’.
Update: Part 2 is now available.