Sie sind auf Seite 1von 16

Ice Tea 09

SSHHAARREE TTOO BBEE SSHHAARREEDD

    

[Android] CardView and


RecyclerView in Material Design
Posted by Trinh Le on December 19, 2014 in Android, Java

Firstly, to have some visual view about this post, you can take a look at this demo video:

Android CardView and RecyclerView in Material Design

A – C a rd V i e w

1 – W h a t i s C a rd V i e w?
CardView was brought along with Android 5.0 Lollipop. It extends FrameLayout and has
rounded background with shadow by default.

CardView is convenient for displaying complex content that has multiple heterogeneous
data type like images, text, videos…
2 – H o w t o u s e C a rd V i e w
To be able to use CardView in your application, you have to declare the required
dependencies like below:

1 dependencies {
2 compile 'com.android.support:appcompat-v7:21.0.0'
3 compile 'com.android.support:cardview-v7:21.0.+'
4 }

After that, in you layout XML file, you also need to declare the card_view namespace:

XHTML
1 xmlns:card_view=http://schemas.android.com/apk/res-auto

Now you can play with CardView

Like other controls, you can add CardView to the layout using XML.

You can add not only TextView into CardView:

1 <android.support.v7.widget.CardView
2 android:layout_width="fill_parent"
3 android:layout_height="wrap_content"
4 card_view:contentPadding="16dp"
5 card_view:cardElevation="2dp"
6 card_view:cardCornerRadius="5dp">
7
8 <LinearLayout
9 android:layout_width="fill_parent"
10 android:layout_height="wrap_content"
11 android:orientation="vertical">
12
13 <TextView
14 style="@style/Base.TextAppearance.AppCompat.Headline"
15 android:layout_width="fill_parent"
16 android:layout_height="wrap_content"
17 android:text="Title" />
18
19 <TextView
20 style="@style/Base.TextAppearance.AppCompat.Body1"
21 android:layout_width="fill_parent"
22 android:layout_height="wrap_content"
23 android:text="Content here" />
24
25 </LinearLayout>
26
27 </android.support.v7.widget.CardView>

But also other kind of controls like ImageView, Button…

1 <android.support.v7.widget.CardView
2 android:layout_width="fill_parent"
3 android:layout_height="wrap_content"
4 card_view:contentPadding="16dp"
5 card_view:cardElevation="2dp"
6 card_view:cardCornerRadius="5dp">
7
8 <LinearLayout
9 android:layout_width="fill_parent"
10 android:layout_height="wrap_content"
11 android:orientation="vertical">
12
13 <ImageView
14 android:layout_width="fill_parent"
15 android:layout_height="150dp"
16 android:src="@drawable/sample"
17 android:scaleType="fitXY"/>
18
19 <TextView
20 style="@style/Base.TextAppearance.AppCompat.Body1"
21 android:layout_width="fill_parent"
22 android:layout_height="wrap_content"
23 android:layout_marginTop="8dp"
24 android:text="Material Design is stunning!!!" />
25
26 </LinearLayout>
27
28 </android.support.v7.widget.CardView>

As you can see on above XML code, CardView provides some properties like

– contentPadding: setting padding for CardView

– cardElevation: new concept in Material Design that represents for z axis

– cardCornerRadius: setting radius for card rounded corner

Demo result:
B – Re c y c le rV ie w

1 – W h a t i s R e c y c l e r V i e w?
RecyclerView is an “upgraded” version of ListView which is more advance and flexible.

RecyclerView is a container for displaying large data sets that can be scrolled efficiently
by maintaining a limited number of views.

RecyclerView also provides some default animations for common item operations like
inserting or removing an item.

2 – H o w t o u s e R e c y c l e r V i e w?
To be able to use RecyclerView in your application, you have to declare the required
dependencies like below:

XHTML
1 dependencies {
2 compile 'com.android.support:appcompat-v7:21.0.0'
3 compile 'com.android.support:recyclerview-v7:21.0.+'
4 }

To use RecyclerView, you have to create 2 essential components:

– LayoutManager: positions items in RecyclerView and determines when to reuse


item views that are no longer visible to the user.

– RecyclerView.Adapter: provides access to data sets items, creates views for items
and binds items info to item view.

2 .1 – L a y o u t M a n a g e r
RecyclerView provides some built-in LayoutManager that you can use immediately:

– LinearLayoutManager: provides similar functions to ListView

– GridLayoutManager: lays out all items in a grid

– StaggeredGridLayoutManager: lays out all items in a staggered grid formation,


supports horizontal and vertical layouts and is able to lay out items in reverse.

2 . 2 – R e c y c l e r V i e w. A d a p t e r
Adapter provides access to all the items in dataset.

Adapter also takes responsibility to create view for each item and replace new content for
the view whenever the original item is no longer visible.

3 – D e m o s im p le Re c y c le rV ie w
In this demo, we will create a simple demo to show you how to use RecyclerView in your
Android application. Actually, it’s quite similar to ListView implementation.

First, place RecyclerView into your layout:

1 <?xml version="1.0" encoding="utf-8"?>


2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent"
5 android:orientation="vertical">
6
7 <android.support.v7.widget.RecyclerView
8 android:id="@+id/recycler_view"
9 android:layout_width="match_parent"
10 android:layout_height="match_parent"/>
11
12 </LinearLayout>

Retrieve it in your code:

1 RecyclerView mRecyclerView;
2
3 @Override
4 protected void onCreate(Bundle savedInstanceState) {
5 super.onCreate(savedInstanceState);
6 setContentView(R.layout.activity_recycler_view);
7 mRecyclerView = (RecyclerView)findViewById(R.id.recycler_view);
8 }

If you’re 100% sure that the item layout size will not change in future, call
setHasFixedSize() method with true value. This will help RecyclerView improve its
performance significantly.
Java
1 mRecyclerView.setHasFixedSize(true);

Next, create a LayoutManager and set it to the RecyclerView. Here, I use the built-in
LayoutManager – LinearLayoutManager this simple demo. In next post, I’ll show you how
to customize LayoutManager.

Java
1 mLayoutManager = new LinearLayoutManager(this);
2 mRecyclerView.setLayoutManager(mLayoutManager);

Then, we need to create the third essential component – the Adapter.

Before touching the Adapter, we need to create a layout for RecyclerView item:

1 <?xml version="1.0" encoding="utf-8"?>


2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:orientation="vertical" android:layout_width="match_parent"
4 android:layout_height="wrap_content"
5 android:padding="@dimen/activity_horizontal_margin">
6
7 <TextView
8 android:id="@+id/tv_recycler_view_item"
9 android:layout_width="wrap_content"
10 android:layout_height="wrap_content"
11 style="@style/Base.TextAppearance.AppCompat.Large"/>
12
13 <LinearLayout
14 android:layout_width="fill_parent"
15 android:layout_height="1dp"
16 android:background="#000"></LinearLayout>
17
18 </LinearLayout>

Then, create SimpleAdapter class with below content:

1 public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.ViewHolder


2
3 List<String> mItems;
4
5 public SimpleAdapter() {
6 super();
7 mItems = new ArrayList<String>();
8 mItems.add("Amazing Spiderman 2");
9 mItems.add("The Guardians of Galaxy");
10 mItems.add("What If");
11 mItems.add("Big Hero 6");
12 mItems.add("The Hunger Game");
13 mItems.add("X-men: Days of Future Past");
14 mItems.add("The Lego Movie");
15 mItems.add("How to Train Your Dragon 2");
16 mItems.add("Maleficent");
17 mItems.add("22 Jump Street");
18 mItems.add("The Maze Runner");
19 mItems.add("Horrible Bosses 2");
20 mItems.add("Night at the Museum 3");
21 }
22
23 @Override
24 public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
25 View v = LayoutInflater.from(viewGroup.getContext())
26 .inflate(R.layout.recycler_view_simple_item, viewGroup, false);
27 ViewHolder viewHolder = new ViewHolder(v);
28 return viewHolder;
29 }
30
31 @Override
32 public void onBindViewHolder(ViewHolder viewHolder, int i) {
33 viewHolder.itemView.setText(mItems.get(i));
34 }
35
36 @Override
37 public int getItemCount() {
38 return mItems.size();
39 }
40
41 class ViewHolder extends RecyclerView.ViewHolder{
42 public TextView itemView;
43 public ViewHolder(View itemView) {
44 super(itemView);
45 this.itemView = (TextView)itemView.findViewById(R.id.tv_recycler_view_
46 }
47 }
48 }

As you can see in the SimpleAdapter class:

– Constructor: where we get the dataset that can be passed from parameter or
created inside the constructor

– ViewHolder class: extends ViewHolder and contains all components, controls of


item view

– onCreateViewHolder(): where we inflate the item layout and create ViewHolder

– onBindViewHolder(): where we manipulate item info into ViewHolder’s


components and controls

– getItemCount(): return the dataset size

After that, we need to create an instance of the Adapter and assign to RecyclerView:

Java
1 RecyclerView.Adapter mAdapter;
2 mAdapter = new SimpleAdapter();
3 mRecyclerView.setAdapter(mAdapter);

Run the application and enjoy the result:


C – C o m b i n e C a rd V i e w a n d R e c y c l e r V i e w
After 2 sections above, we all know that CardView and RecyclerView are very powerful
and flawless components.

In this section, I’ll show you how to combine CardView and RecyclerView to create
stunning view displaying a dataset.

Firstly, create the layout for each item using CardView:

1 <?xml version="1.0" encoding="utf-8"?>


2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 xmlns:card_view="http://schemas.android.com/apk/res-auto"
4 android:layout_width="match_parent"
5 android:layout_height="match_parent"
6 android:orientation="vertical">
7
8 <android.support.v7.widget.CardView
9 android:layout_width="fill_parent"
10 android:layout_height="wrap_content"
11 card_view:contentPadding="@dimen/activity_horizontal_margin"
12 card_view:cardCornerRadius="3dp">
13
14 <ImageView
15 android:id="@+id/img_thumbnail"
16 android:layout_width="fill_parent"
17 android:layout_height="150dp" />
18
19 <TextView
20 android:id="@+id/tv_movie"
21 android:layout_width="fill_parent"
22 android:layout_height="50dp"
23 android:paddingLeft="@dimen/activity_horizontal_margin"
24 android:paddingRight="@dimen/activity_horizontal_margin"
25 android:layout_gravity="bottom"
26 android:gravity="center_vertical"
27 android:background="#757575"
28 android:alpha="0.8"
29 android:textSize="@dimen/abc_text_size_headline_material"
30 android:text="Test"/>
31
32 </android.support.v7.widget.CardView>
33
34 </LinearLayout>

This demo will display a list of Movie info with name and thumbnail. So that we also need
to create an entity class for Movie:

1 public class Movie {


2 private String mName;
3 private int mThumbnail;
4
5 public String getName() {
6 return mName;
7 }
8
9 public void setName(String name) {
10 this.mName = name;
11 }
12
13 public int getThumbnail() {
14 return mThumbnail;
15 }
16
17 public void setThumbnail(int thumbnail) {
18 this.mThumbnail = thumbnail;
19 }
20 }

Then, create CardAdapter class that similar to SimpleAdapter above. Instead only one
TextView, now the ViewHolder will have the ImageView to display the movie thumbnail as
well.

1 public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder


2 List<Movie> mItems;
3
4 public CardAdapter() {
5 super();
6 mItems = new ArrayList<Movie>();
7 Movie movie = new Movie();
8 movie.setName("The Amazing Spider-Man 2");
9 movie.setThumbnail(R.drawable.spiderman);
10 mItems.add(movie);
11
12 movie = new Movie();
13 movie.setName("X-men: Days of Future Past");
14 movie.setThumbnail(R.drawable.xmen);
15 mItems.add(movie);
16
17 movie = new Movie();
18 movie.setName("The Hunger Game");
19 movie.setThumbnail(R.drawable.hungergame);
20 mItems.add(movie);
21
22 movie = new Movie();
23 movie.setName("Guardians of the Galaxy");
24 movie.setThumbnail(R.drawable.guardians_of_the_galaxy);
25 mItems.add(movie);
26
27 movie = new Movie();
28 movie.setName("Maleficent");
29 movie.setThumbnail(R.drawable.maleficent);
30 mItems.add(movie);
31
32 movie = new Movie();
33 movie.setName("How to Train Your Dragon 2");
34 movie.setThumbnail(R.drawable.howtotrainyourdragon);
35 mItems.add(movie);
36
37 movie = new Movie();
38 movie.setName("What If");
39 movie.setThumbnail(R.drawable.whatif);
40 mItems.add(movie);
41 }
42
43 @Override
44 public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
45 View v = LayoutInflater.from(viewGroup.getContext())
46 .inflate(R.layout.recycler_view_card_item, viewGroup, false);
47 ViewHolder viewHolder = new ViewHolder(v);
48 return viewHolder;
49 }
50
51 @Override
52 public void onBindViewHolder(ViewHolder viewHolder, int i) {
53 Movie movie = mItems.get(i);
54 viewHolder.tvMovie.setText(movie.getName());
55 viewHolder.imgThumbnail.setImageResource(movie.getThumbnail());
56 }
57
58 @Override
59 public int getItemCount() {
60 return mItems.size();
61 }
62
63 class ViewHolder extends RecyclerView.ViewHolder{
64
65 public ImageView imgThumbnail;
66 public TextView tvMovie;
67
68 public ViewHolder(View itemView) {
69 super(itemView);
70 imgThumbnail = (ImageView)itemView.findViewById(R.id.img_thumbnail
71 tvMovie = (TextView)itemView.findViewById(R.id.tv_movie);
72 }
73 }
74 }

Finally, invoke an instance of CardAdapter and set it to RecyclerView:

Java
1 mAdapter = new CardAdapter();
2 mRecyclerView.setAdapter(mAdapter);

Now you can run and enjoy the result when combine CardView and RecyclerView:
D – D o w n l o a d S o u rc e C o d e C a rd V i e w a n d R e c y c l e r V i e w i n
M a te r ia l D e s ig n
https://github.com/trinhlbk1991/DemoCardViewRecyclerView

http://www.mediafire.com/download/5s94lj10cyy4rj3
/DemoCardViewRecyclerView.zip

SShhaarree tthhiiss::

 Facebook 13  LinkedIn 1  Google  Twitter  More

LLiikkee tthhiiss::

 Like
Be the first to like this.

Related

[Android] Apply [Android] Drawer [Android] Android


Material Design to Navigation Menu with Action Bar
Pre-Lollipop Devices Material Design Style
using AppCompat v21

 Android, Java

 android 5.0, cardview, lollipop, material design, recyclerview


← [Android] Apply Material Design to Pre-Lollipop Devices using AppCompat v21
[Android] Drawer Navigation Menu with
Material Design Style →

9 t h o u g h t s o n “ [ A n d ro i d ] C a rd V i e w a n d R e c y c l e r V i e w i n
M a te r i a l D e s i g n”

Pingback: ANDROID RECYCLERVIEW | Moringa School

MDq MAY 22, 2015 / REPLY

How can I make it clickable??

Trinh Le Post author MAY 28, 2015 / REPLY

Hi,

If you want to make any View clickable, just set the on click
listener for it. Example:

button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, “Button Clicked”,
Toast.LENGTH_SHORT).show();
}
});

joywin JUNE 4, 2015 / REPLY

how to make it clickable explain in brief

Trinh Le Post author JUNE 5, 2015 / REPLY


Hi,

If you want to make any View clickable, just set the on click
listener for it. Example:

button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, “Button Clicked”,
Toast.LENGTH_SHORT).show();
}
});

Omar JUNE 21, 2015 / REPLY

Can i use recyclerview using sqlite databsae

Trinh Le Post author JUNE 21, 2015 / REPLY

Absolutely! You can use RecyclerView whenever you have a


data set

sribouty SEPTEMBER 22, 2015 / REPLY

would u explain how to put all the query from SQLite to


the cardview?

vamsi SEPTEMBER 14, 2015 / REPLY

Is it possible When we click on a content/card then it shows in


full screen in recycler View.
Le a v e a R e p l y

Subscribe to Blog via Email


Enter your email address to subscribe to this blog and receive notifications of new posts
by email.

Join 27 other subscribers

Subscribe

Support Ice Tea 09

Like Ice Tea 09

Ice Tea 09
173 likes

Like Page Contact Us

Be the first of your friends to like this

Before I Die I Want To…


Top Posts
[Android] CardView and RecyclerView in Material Design

[Android] Drawer Navigation Menu with Material Design Style

[Android] Use Existing SQLite Database in Android App

[Android] Parse JSON Request using Volley and GSON

[Android] Card Flip Animation

Archives

Select Month

Categories

Select Category

Friends
Tung Nguyen

Tân Nguyễn Blog

Free APK Store

Meta
Log in Entries R S S
Comments R S S WordPress.org

© 2015 Ice Tea 09 - Theme: Patus by FameThemes.

Privacy Policy - Terms and Conditions

Das könnte Ihnen auch gefallen