The RecyclerView, like the GridView and ListView, allow you to create lists of elements either through lists or cells; the RecyclerView can be seen as a more flexible, powerful and updated version than these and surely at some point they will be their definitive replacement; the way it works is the same used as its predecessors as you can see in this image:

Adapter that acts as a bridge between the data and the view.
Add the support library to work with the RecyclerView and CardView
In the same way that we added the necessary dependencies to add multiple elements of the Support Library (specifically the FloatActionButton), it is necessary to add the dependencies to be able to use the RecyclerView and CardView in our project; add the following dependencies in the build.gradle file:
compile 'com.android.support:cardview-v7:23.0.1'
compile 'com.android.support:recyclerview-v7:23.0.1'app/build.gradle
The CardView
The RecyclerView and the CardView are part of the support library; The CardView inherits from the ViewGroups more directly from the FrameLayout and therefore it is an element that allows us to define many other elements within it, such as the following:
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="2dp"
card_view:cardCornerRadius="1dp">
<RelativeLayout
android:id="@+id/parent_body_rl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FF5722"
android:orientation="vertical"
android:padding="2dp">
<LinearLayout
android:id="@+id/parent_body_ll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="2dp">
<LinearLayout
android:id="@+id/color_ll"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_margin="10dp"
android:background="#FF0000"
android:orientation="vertical" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:padding="2dp">
<TextView
android:id="@+id/name_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="texto 1"
android:textColor="#FFFFFF"
android:textSize="25sp" />
<TextView
android:id="@+id/description_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/info_text"
android:padding="10dp"
android:text="texto 2"
android:textColor="#FFFFFF"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>Obtaining the following result:

In other words, we can use the CardView in conjunction with the RecyclerView; where the CardView defines the items of the list.
Creating a RecyclerView
First of all, you need to add a RecyclerView element in the layout of our Activity or Fragment:
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/recycler_view"
/>Like any other element, to reference the previous RecyclerView from our Activity we use the following Java code:
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recycler_view);Specifying the positioning of the RecyclerView with the Layout Manager
From here we can appreciate some changes with respect to the moment of creating the ListView and GridView; to define the position in which we want our list of items to render (in the form of lists or cells):

We use the following Java code so that the elements are positioned in the list through listings:
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context); recyclerView.setLayoutManager(LinearLayoutManager);Or the GridLayoutManager so that the elements are positioned in the list via cells:
GridLayoutManager gridLayoutManager = new GridLayoutManager(context); recyclerView.setLayoutManager(gridLayoutManager);Specifying the data and the model
For greater ease when manipulating the data, we will create a Person model to specify a list with our data that we will later pass to the Adapter.
public class Person {
String name;
String description;
String color;
Person(String name, String description,String color){
this.name = name;
this.description = description;
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}Nothing out of the ordinary, the person has a name, a description (age, etc.) and the favorite color.
Defining the Adapter
The Adapter used by RecyclerViews are very similar to those used by ListViews and GridViews in terms of their structure and behavior; in addition to this, we are going to use the ViewHolder to more easily reference the elements that interest us in our list; the definition of the Adapter below:
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ViewHolder>{
private ArrayList<Person> persons;
// Provee una referencia a cada item dentro de una vista y acceder a ellos facilmente
public static class ViewHolder extends RecyclerView.ViewHolder {
// Cada uno de los elementos de mi vista
public TextView nameTextView,descriptionTextView;
public CardView cardView;
public LinearLayout colorLl;
public RelativeLayout parentBodyRl;
public ViewHolder(View v) {
super(v);
parentBodyRl = (RelativeLayout) v.findViewById(R.id.parent_body_rl);
cardView = (CardView) v.findViewById(R.id.card_view);
nameTextView = (TextView) v.findViewById(R.id.name_tv);
descriptionTextView = (TextView) v.findViewById(R.id.description_tv);
colorLl = (LinearLayout) v.findViewById(R.id.color_ll);
}
}
// Constructor
public ListAdapter(ArrayList<Person> persons) {
this.persons = persons;
}
// Create new views (invoked by the layout manager)
@Override
public ListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// inflo la vista (vista padre)
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_adapter, parent, false);
// creo el grupo de vistas
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Reemplaza en contenido de la vista
@Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
viewHolder.nameTextView.setText(persons.get(position).getName());
viewHolder.descriptionTextView.setText(persons.get(position).getDescription());
}
// Retorna el tamano de nuestra data
@Override
public int getItemCount() {
return persons.size();
}
}
As we see in the previous code, there are three methods that we must override:
The getItemCount() method that should return the size of the list, or what is the same, the size of our list of items that will be displayed in the list.
The onCreateViewHolder() method allows us to initialize all the elements that make up our previously defined ViewHolder class; we also define the layout (which can vary for each element) that each element uses. It is also possible to define the events in this function.
In the onBindViewHolder() method, the values of the different fields must be defined or bound.
Invoking the above Adapter
From our Activity or Fragment, we create an object of the Adapter defined above:
ListAdapter listAdapter = new ListAdapter(persons); audioRv.setAdapter(listAdapter);And when running our application on the emulator or physical device:

Conclusions
In this post we took the first steps with the RecyclerView and CardView available in the latest versions of Android and later through the Support Library; we could notice that the operation and the implementation are very similar to what we are used to with the GridView and ListView; In the following posts we will see how easy it is to implement other functionalities to the RecyclerView and CardView, such as the swipe and some simple animations to hide sections of the CardView.
Creando un RecyclerView
In a previous entry we talked a little about the future (and present) of Kotlin in the world of Android application development using this programming language that little by little tries to replace Java as the primary and official language in the development of Android applications; one of the reasons that are exposed in that entry that you can consult, is the simplification of the different elements that we can develop, an example of this is the development of the RecyclerView of an adapter as we will see below.
To give continuity and support to some of the arguments made in the previous entry, today we will see how to make a simple list of elements through a RecyclerView clearly using Kotlin as programming language; that is, no Java.
RecyclerView on Android with Kotlin: Same approach, events, classes but different syntax
The classes to use to create a list with RecyclerView with Kotlin will be the same used for the development of a Recyclerview using Java. the model class, adapter and of course the activity, we will also need a couple of layouts; one for the activity and another for the list that would become our RecyclerView.
The model class of our adapter
Here we must define the class or model that will define our object, if it is a person, if it is a car, if it is a computer or in this case we define an Item class that will have an identifier and a description that would be one of the simplest things that We can define:
data class Item(val id: Long, val title: String, val description: String)The main Activity: the one that implements the Adapter
A novelty that Kotlin has with respect to Java is that through the name of the element identifier in the layout; (for example android:id="@+id/rv_item" to define the identifier of the RecyclerView in the layout of our activity) it is enough to reference in the activity or class that establishes the content of said view, and therefore in Kotlin it is no longer necessary to set the value of such variables as it is done in Java-Android; this is achieved by means of a plugin/include that is imported at the time of making the reference and automatically by Android Studio (import kotlinx.android.synthetic.main.activity_main.*):
RecyclerView rv_item = (RecyclerView) findViewById(R.id.rv_item);
Although we can also make the classic version that we use in Android with Java; finally the Activity code:
import android.content.Context
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import mykotlin.dl.recyclerview.recyclerviewkotlin.adapter.ItemAdapter
import mykotlin.dl.recyclerview.recyclerviewkotlin.model.Item
import kotlin.dl.recyclerview.recyclerviewkotlin.R
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val items = getLists()
rv_item.layoutManager = LinearLayoutManager(this)
rv_item.hasFixedSize()
rv_item.adapter = ItemAdapter(items)
rv_item.layoutManager = LinearLayoutManager(this)
rv_item.adapter = ItemAdapter(items)
}
fun getLists(): ArrayList<Item> {
var lists = ArrayList<Item>()
lists.add(Item(1, "Item 1", "Descripcion 1"))
lists.add(Item(1, "Item 2", "Descripcion 2"))
lists.add(Item(1, "Item 3", "Descripcion 3"))
lists.add(Item(1, "Item 4", "Descripcion 4"))
return lists;
}
}The previous activity is in charge of defining the layout type (which in this case will be a ListView type list) and populating (filling) an Item type ArrayList with some test data and of course, creating an instance of the adapter that will create the list that we define in the next block within this entry.
The adapter class: Defines the logic and behavior of the RecyclerView
The adapter class, which is the one that is in charge of defining the behavior and style of each one of the components of the list, as we can see, makes the same name to override each one of the functions inherited from the RecyclerView.Adapter class; again we use the name of the items of each element defined in the view without needing to reference them first (eg: itemView.tv_description with the autogenerated import from the IDE import kotlinx.android.synthetic.main.adapter_item.view.*):
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.adapter_item.view.*
import kotlin.dl.recyclerview.recyclerviewkotlin.R
import mykotlin.dl.recyclerview.recyclerviewkotlin.model.Item
class ItemAdapter (val userList: ArrayList<Item>) : RecyclerView.Adapter<ItemAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.adapter_item, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindItems(userList[position])
}
override fun getItemCount(): Int {
return userList.size
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindItems(item: Item) {
itemView.tv_title.text=item.title
itemView.tv_description.text=item.description
}
}
}We override the usual methods, onBindViewHolder to return the current item getItemCount to return the size of the collection of objects onCreateViewHolder to specify the layout of our list as well as compose the view and finally the ViewHolder class that allows defining each of the compound elements in our layout and specify its content and of course the constructor method where we initialize the fundamental components or that we require.
The layout of our activity
As for the layouts, they remain exactly the same as the ones we use in Java-Android; More than that there is not much to say, from our activity we specify a RecyclerView element and the other layout is the one specified by employee for our list:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="mykotlin.dl.recyclerview.recyclerviewkotlin.MainActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:id="@+id/rv_item"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</android.support.constraint.ConstraintLayout>The layout of our list
<?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:orientation="vertical">
<TextView
android:id="@+id/tv_title"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tv_description"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>As we can see the logic used is the same that we use with Java, I invite you to review some of the previous entries that are listed at the end of this entry and compare them with these to see the similarity that exists between the two.
Finally, we get a list like this:

You can give it the style you want by modifying the layout or the style XML as you prefer, to give it the design to your liking; The idea in this post was to show how to create a RecyclerView using Kotlin as programming language and not focus on the design.
Conclusion
As we can see, Kotlin is a complete language that allows us to develop Android applications easier (at least as far as syntax is concerned) than with Java.
Creating a filter for the RecyclerView in Android

In this entry we will see how to create a filter for our RecycleView; In a previous entry we saw how to create lists through lists and grids with the RecycleView Today we will see the same process but with an extra which consists of creating a filter for the previous list through (logically) a search field with a simple EditText.
In our adapter we will create an extra class that we will call CustomFilter that will look like this:
public class CustomFilter extends Filter {
private ListAdapter listAdapter;
private CustomFilter(ListAdapter listAdapter) {
super();
this.listAdapter = listAdapter;
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
personsFilter.clear();
final FilterResults results = new FilterResults();
if (constraint.length() == 0) {
personsFilter.addAll(persons);
} else {
final String filterPattern = constraint.toString().toLowerCase().trim();
for (final Person person : persons) {
if (person.getName().toLowerCase().contains(filterPattern)) {
personsFilter.add(person);
}
}
}
results.values = personsFilter;
results.count = personsFilter.size();
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
this.listAdapter.notifyDataSetChanged();
}
}As well as adding an implements to implement the Filterable class in our Adapter:
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ViewHolder> implements Filterable {
private ArrayList<Person> persons;
private ArrayList<Person> personsFilter;
private CustomFilter mFilter;
...
}
public ListAdapter(ArrayList<Person> persons) {
this.persons = persons;
this.personsFilter = new ArrayList<>();
this.personsFilter.addAll(persons);
this.mFilter = new CustomFilter(ListAdapter.this);
}In our adapter and the associated getFilter method we override:
@Override
public Filter getFilter() {
return mFilter;
}A small piece of information that we have to do in our adapter is to create another list which contains the data filtered by the user and another list that contains the total data that makes up our list without applying any filter; Taking this into account, our constructor and other control methods will be defined as follows:
// Constructor
public ListAdapter(ArrayList<Person> persons) {
this.persons = persons;
this.personsFilter = new ArrayList<>();
this.personsFilter.addAll(persons);
this.mFilter = new CustomFilter(ListAdapter.this);
}
...
@Override
public int getItemCount() {
return personsFilter.size();
}
...
@Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
viewHolder.nameTextView.setText(personsFilter.get(position).getName());
viewHolder.descriptionTextView.setText(personsFilter.get(position).getDescription());
viewHolder.colorLl.setBackgroundColor(Color.parseColor(personsFilter.get(position).getColor()));
}As you can see we use the filterable ArrayList instead of the complete ArrayList.
We have the adapter ready, now we need to configure the search field in our activity or fragment to be able to filter our list and the associated events; for this we will use an EditText as we mentioned before:
etSearchBox = (EditText) findViewById(R.id.etSearchBox);And the listener event (listener) that is activated when entering/removing text on it:
etSearchBox.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
listAdapter.getFilter().filter(s.toString());
}
@Override
public void afterTextChanged(Editable s) {
}
});As you can see, when changing the text, the filter method is called, passing the text to be filtered as a parameter.
You can specify the behavior of the filter in the adapter's CustomFilter class by defining the behavior at which time the personsFilter is populated when performing the comparison:
if (person.getName().toLowerCase().contains(filterPattern))In our case we are interested that it is NOT case sensitive and that it contains (contains) the key word or section and thus have a fairly flexible filter, but you can express it as you wish.
I agree to receive announcements of interest about this Blog.
The RecyclerView, like the GridView and ListView, allow you to create lists of items either through lists or cells and are a more flexible, powerful and updated version than the GridView ListView.