RecyclerView and CardView's are easy ways to add a professional look to your app.  They are good for previewing top level features of your app like, say, a concert.  Each card could be a different concert for bands the user likes.  When you click on the card, you are brought to a detailed page of the concert events like time, venue, ticket cost, etc. 

The RecyclerView is an advanced list-view-like feature of Android's material design.  It is meant to be used when the items in the list change during runtime in response to user interaction. 

The CardView is one item in the list except that the card can contain it's own custom layout that you define however you want. 

Here's how to use these features.

Start with the dependencies

First, open your build.gradle (Module:app) file and add the dependencies required for the CardView and RecyclerView.

1

Make sure the CardView and RecyclerView version's match the appcompat version number placed here when your project was created.

Create the CardView layout

Right click on your Layout folder and create a new layout.  I named mine c_main.xml (c for card).  Add this code to create the card. 

(As a side note here, I often prefix the layout name with the first letter of the type of layout it is.  a for activities, f for fragments, d for dialogs, etc.)

<android.support.v7.widget.CardView
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="64dp"
     android:layout_margin="8dp">
 
     <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:orientation="horizontal">
 
         <ImageView
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_gravity="center"
             android:layout_margin="4dp"
             android:adjustViewBounds="false"
             android:cropToPadding="false"
             android:src="@drawable/ic_library_books_black_24dp"/>
 
         <TextView
             android:id="@+id/CardTextView"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:gravity="center"
             android:text="Party on, Wayne"/>
     </LinearLayout>
 </android.support.v7.widget.CardView>

 

If you switch to the design tab in the layout file and get some errors, follow its instructions and try to build your project.  If that fails, go to the Build menu at the top and click on Clean Project.

2

We'll also need to add a vector asset to use for the ImageView in the layout.  To do this, right click on your Drawable folder and go to New -> Vector Asset.

3

Choose an icon and finish importing it into your library.  It is now in your Drawable folder.  This is the drawable asset we referenced in the ImageViews "android:src..." attribute.  Change the name to the name of the image you used here.

Create a custom adapter

In order to use our cards, we must create an adapter.  The purpose of an adapter is to tell the cards what they should look like in the RecyclerView and what actions they should perform when interacted with, among some other bookkeeping items.  RecyclerView's are more complex so we must roll our own adapter when we use them. 

Right click on your project folder and add a new class.  I called mine MainCardAdapter.  Since you may have multiple CardView's in your app, I recommend naming them with the activity they will be used in.

This is the adapter.

public class MainCardAdapter extends RecyclerView.Adapter<MainCardAdapter.ViewHolder>
 {
     private Context context;
     List<String> items; // This will hold the strings to display on each card.
 
     public MainCardAdapter(Context context)
     {
         this.context = context;
         items = new ArrayList<>();
     }
 
     // Inflate card view
     public MainCardAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int position)
     {
         View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.c_main, viewGroup, false);
         return new ViewHolder(view);
     }
 
     public int getItemCount()
     {
         return items.size();
     }
 
     public void onBindViewHolder(MainCardAdapter.ViewHolder viewHolder, int position)
     {
         viewHolder.SetViews(this);
     }
 
     // Call from MainActivity to add cards
     public void AddCard(String message)
     {
         items.add(message);
         notifyDataSetChanged();
     }
 
   // Separate class that is used to hold the individual views for each card
     public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
     {
         public MainCardAdapter adapter;
         TextView tv;
 
         public ViewHolder(View view)
         {
             super(view);
             view.setOnClickListener(this);
             // This is where you set individual view properties like onClickListeners...
             tv = (TextView)view.findViewById(R.id.CardTextView);
         }

        // This is where you set references to your View objects to interact with later.

        // This is also where you would put onClickListener properties and the like
         public void SetViews(MainCardAdapter adapter)
         {
             this.adapter = adapter;
             tv.setText(items.get(getAdapterPosition()));
         }

        // To detect a click on the whole card.  If you want to click on just one individual view, do that

        // in the above method
         @Override
         public void onClick(View v)
         {
             Toast.makeText(context, "You clicked card: " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
         }
     }
 }

 

I commented the most important pieces of this code so hopefully it makes sense.  If not, leave your questions below and I'll answer them!

Create the RecyclerView

In activity_main.xml, insert a RecyclerView like so. 

<android.support.v7.widget.RecyclerView
    android:id="@+id/RecyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>

Wire it up!

This is the entire MainActivity class code.  Create a private method that will handle the initial setup of the RecyclerView.  Call adapter.AddCard("words"); to add cards.

public class MainActivity extends AppCompatActivity
{
    RecyclerView recyclerView;
    MainCardAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = (RecyclerView)findViewById(R.id.RecyclerView);
        SetupRecyclerView();
        adapter.AddCard("Party on, Wayne");
        adapter.AddCard("Party on, Garth");
    }

    private void SetupRecyclerView()
    {
        recyclerView = (RecyclerView)findViewById(R.id.RecyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        adapter = new MainCardAdapter(getApplicationContext());
        recyclerView.setAdapter(adapter);
    }
}

Now run your code!  When you click on the cards, you will get a toast notification telling you which number of card you clicked on.

Results

When you're done it should look something like this.

4

There you have it, a simple RecyclerView!

We'll extend the functionality in a later post but if you'd like to play around with it, add some views on screen and interact with them by creating methods in the adapter.

Thanks for joining and leave a comment below if you have any questions.  I read them all!

Leave a Reply

Your email address will not be published. Required fields are marked *