Android CardView Tutorial - CodeProject
Android CardView Tutorial - CodeProject
Android CardView Tutorial - CodeProject
1M
Sign up for our free weekly Mobile Newsletter. Sign in
×
articles Q&A forums stuff lounge ? Search for articles, questions, tips
Android CardView Tutorial We have already discussed about RecyclerView in the following
tutorial Listing Items using RecyclerView and shown a recyclerview example in android
studio. Today we will discuss about CardView in Android SDK which was introduced with
the android material design through the
Today we will discuss about CardView in Android SDK which was introduced with the
android material design through the support v7 library. We will show you how CardView
can be implemented in a RecyclerView list. After reading this article you should feel
comfortable creating Lists and Cards view in your android app.
CardView provides a more advanced and flexible way of implementing complex and
custom listview with more functionality that is required nowadays for our apps.
We would be creating an Android CardView Example List app, where we will list 7 wonders
of Modern World along with a Like Button and a Share Button. On clicking the Like Button
it will get highlighted and show a message. Clicking the Share Button will provide you
options to share the photo of the Item you clicked. After completion, the app would look
like as shown in the video.
Pre-requisites
A new project will be created and gradle will resolve all the dependencies.
We would be listing wonders of the world so create a new WonderModel.java class
which will have all the field as well getter,setter methods required for a wonder. Add the
following code to the class
WonderModel.java
package com.androidtutorialpoint.cardviewtutorial;
String cardName;
int imageResourceId;
int isfav;
int isturned;
compile 'com.android.support:recyclerview-v7:23.1.1'
compile 'com.android.support:cardview-v7:23.1.1'
Now, Gradle will sync your project and add the dependencies.
Add a RecyclerView
1. Create a layout file by Right-clicking on the res/layout directory and selecting New →
Layout resource file. Name the file fragment_card.xml and click OK to create the file.
Open the file add the following code.
fragment_card.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_left_margin"
android:paddingRight="@dimen/activity_right_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MyActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/cardView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Let’s create a layout file. Create a new Layout resource file name it recycle_items.xml
and paste the following code.
recycle_items.xml
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
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_margin="5dp"
card_view:cardCornerRadius="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="@dimen/card_height"
android:orientation="vertical"
android:weightSum="4">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="3.2"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal">
<ImageView
android:id="@+id/coverImageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
d id l i " "
android:layout_gravity="center"
android:scaleType="centerCrop"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="left|bottom"
android:background="@android:drawable/screen_background_dark_transparent"
android:orientation="vertical">
<TextView
android:id="@+id/titleTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:textSize="@dimen/text_size"
android:textColor="#FFFFFF"
android:textStyle="bold" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="0.8"
android:gravity="center|right"
android:orientation="horizontal">
<ImageView
android:id="@+id/likeImageView"
android:layout_width="@dimen/icon_width"
android:layout_height="@dimen/icon_height"
android:padding="@dimen/icon_padding"
android:src="@drawable/ic_like" />
<ImageView
android:id="@+id/shareImageView"
android:layout_width="@dimen/icon_width"
android:layout_height="@dimen/icon_height"
android:padding="@dimen/icon_padding"
android:src="@drawable/ic_share" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
1. Create a new fragment, name it CardFragment.java and add the following code.
Let’s use arrays to store the name and ImageId for each 7 wonders. We have already
added the photos of the places to the drawable folder. You can download the code by
clicking on the Download Now Button provided at the top.
CardFragment.java
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeList();
getActivity().setTitle("7 Wonders of the Modern World");
}
Following is the implementation of the intializeList() method. Add this method
after the onCreate() method in the file.
Hide Copy Code
for(int i =0;i<7;i++){
3. A view Holder is required to hold on to the views, so add the following code.
Hide Shrink Copy Code
public MyViewHolder(View v) {
super(v);
titleTextView = (TextView)
v.findViewById(R.id.titleTextView);
coverImageView = (ImageView)
v.findViewById(R.id.coverImageView);
likeImageView = (ImageView)
v.findViewById(R.id.likeImageView);
shareImageView = (ImageView)
v.findViewById(R.id.shareImageView);
likeImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int id = (int)likeImageView.getTag();
if( id == R.drawable.ic_like){
likeImageView.setTag(R.drawable.ic_liked);
likeImageView.setImageResource(R.drawable.ic_liked);
Toast.makeText(getActivity(),titleTextView.getText()+" added to
favourites",Toast.LENGTH_SHORT).show();
}else{
likeImageView.setTag(R.drawable.ic_like);
likeImageView.setImageResource(R.drawable.ic_like);
}
}
});
shareImageView.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
Uri imageUri =
Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE +
"://" +
getResources().getResourcePackageName(coverImageView.getId())
+ '/' + "drawable" + '/' +
getResources().getResourceEntryName((int)coverImageView.getTag()));
The above code extends the RecyclerView.ViewHolder class and references the
ImageView and the TextViews for each view it will be holding.
On clicking the like button the state of the button is toggled and it shows a
corresponding message that it has added/removed the item to/from favourites.
In the OnClick() for the shareImageView an Intent is fired that shows an option
to share the image of the place you have selected.
4. Next, extend the RecyclerView.Adapter class, this adapter is link between the
RecyclerView and the data which we want to list. It creates required
ViewHolders and also binds the ViewHolder to data from the WonderModel
class.
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,int
viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycle_items, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(final MyViewHolder holder, int
position) {
holder.titleTextView.setText(list.get(position).getCardName());
holder.coverImageView.setImageResource(list.get(position).getImageResourc
eId());
holder.coverImageView.setTag(list.get(position).getImageResourceId());
holder.likeImageView.setTag(R.drawable.ic_like);
@Override
public int getItemCount() {
return list.size();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
return view;
}
CardFragment.java
package com.androidtutorialpoint.cardviewtutorial;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeList();
getActivity().setTitle("7 Wonders of the Modern World");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,int
viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.recycle_items, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(final MyViewHolder holder, int
position) {
holder.titleTextView.setText(list.get(position).getCardName());
holder.coverImageView.setImageResource(list.get(position).getImageResourc
eId());
holder.coverImageView.setTag(list.get(position).getImageResourceId());
holder.likeImageView.setTag(R.drawable.ic_like);
@Override
public int getItemCount() {
return list.size();
}
}
public MyViewHolder(View v) {
super(v);
titleTextView = (TextView)
v.findViewById(R.id.titleTextView);
coverImageView = (ImageView)
v.findViewById(R.id.coverImageView);
likeImageView = (ImageView)
v.findViewById(R.id.likeImageView);
shareImageView = (ImageView)
v.findViewById(R.id.shareImageView);
likeImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int id = (int)likeImageView.getTag();
if( id == R.drawable.ic_like){
likeImageView.setTag(R.drawable.ic_liked);
likeImageView.setImageResource(R.drawable.ic_liked);
Toast.makeText(getActivity(),titleTextView.getText()+" added to
favourites",Toast.LENGTH_SHORT).show();
}else{
likeImageView.setTag(R.drawable.ic_like);
likeImageView.setImageResource(R.drawable.ic_like);
}
});
shareImageView.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
Uri imageUri =
Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE +
"://" +
getResources().getResourcePackageName(coverImageView.getId())
+ '/' + "drawable" + '/' +
getResources().getResourceEntryName((int)coverImageView.getTag()));
}
});
}
}
for(int i =0;i<7;i++){
}
}
}
MainActivity
package com.androidtutorialpoint.cardviewtutorial;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
fragment = new CardFragment();
;
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit();
}
}
}
activity_main.xml
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</FrameLayout>
Run the App and you should see a scrollable List of 7 Wonders of the world. Try
scrolling through and clicking Like or Share to share the photo. Please comment in
case you have any doubts or suggestions.
What’s Next
We hope this tutorial will help you getting started with RecyclerView and CardView on
Android. You can reuse the cards to create beautiful apps that have a list interface.
License
This article, along with any associated source code and files, is licensed under The Code
Project Open License (CPOL)
Share
Hello Developer!
As a co-founder, I would like to welcome you to the Android Tutorial Point community!. I
hope you get the best possible value at of our platform. Stick with us for a while, and we
promise you will become an $$Android Rockstar$$!
Android Tutorial Point is the right platform if you want to learn about android
development. We have a broad collection of tutorials on different aspects of Android
Development and it is growing rapidly. Here at Android Tutorial Point we thrive to deliver
the best tutorials. In this direction, we are trying to create a community that will cater to
your needs, whether you are a beginner or a seasoned veteran. For the beginners that are
getting started on Android Development
journey, we would suggest you to begin with our Android Basics Tutorial available at
http://www.androidtutorialpoint.com/category/basics/ . Here, we feature articles on how
to start with Android programming.
All the best from the Android Tutorial Point team. Don't forget to subscribe our blog for
latest android tutorials. You can reach out to us at our Facebook page
https://www.facebook.com/androidtutorialpoint/ or Add us on Twitter
https://twitter.com/androidtutpoint/ . Any ideas or suggestions? Shoot us an email at
androidtutorialspoint@gmail.com
You may also be interested in...
Android Sensor Fusion Tutorial A Flexible Direct2D Pianoroll for Your Music Apps
Android ExpandablelistView Tutorial with Android An Advanced Splash Screen for Android App
Custom Adaptor
Search Comments