This article presumes that you know at least basics of Android Development, including using Android Studio and creating a simple one-screen app with a list in it. Also, Kotlin. Now that is clear, let's head to using the RecyclerView.
If you want to add a list to your app, the obvious choice is a RecyclerView. Let's use it, and add some cards for the list to make it look cool! (Who does not like cards?)
We start with creating a simple application in Android Studio by clicking New Project... and then using the Basic Activity template for the application. You need to choose Kotlin as Language, and after clicking Finish, add following dependencies in the app/build.gradle file.
Write the base code
Let's write the necessary code, after which we can experiment with the list.
In Activity class, we initialize the RecyclerView with a LayoutManager, and an Adapter for the child items.
The layout contains various elements, but the important one is the RecyclerView.
The layout represents the view for each child item. It has a simple CardView.
Obviously, we have to write an Adapter. Though this article does not include its explanation, here's the code.
Now running the app should give us a nice looking list of cards.
The uneven spacing issue
Oh, but it seems the space between cards is more than the top card and containers top.
We have two ways to fix this.
Change the item layout to have startMargin and endMargin to 16dp and give the card either of the top or bottom margin. In this case, also we need to add some padding to the RecyclerView, either to the top/bottom.
Another way is to add top and bottom padding to the RecyclerView. This way is better since it keeps the symmetry in the item view, and you don't have to remember that you gave the card top margin or the bottom margin.
I'm going to go with the second way. There might be other ways to do this. Please let me know if you find any other.
After adding paddingTop and paddingBottom to the RecyclerView, rerun the app.
It results in the following screen:
It does look right now. But wait! When you scroll, you can see the gap between the toolbar and the first card.
The weird spacing issue
Also, there is space between the bottom card and the parent, and when you scroll, the scrim looks not so good.
RecyclerView is a ViewGroup, and by default, a ViewGroup clips it's children for padding, or in other words, it won't let the children view draw in the padding area.
We can change this behavior easily by adding clipToPadding to the RecyclerView.
If we set clipToPadding to false, RecyclerView allows the cards to be drawn in the padding area. Now the RecyclerView becomes:
Rerun the app, and you see the magic!
We used the attribute clipToPadding to create better-looking RecyclerView.