Về cơ bản, CardView
giống như FrameLayout
, có hỗ trợ bo tròn bốn góc và hiệu ứng đổ bóng. CardView
thường được sử dụng làm container cho các dòng trong ListView
và RecyclerView
.
CardView trong Android
Không như Button
hay TextView
, mặc định trong Android SDK không có sẵn widget này mà phải import trong dependences để Android Studio tự cài đặt widget này.
Vào File → Project Structure... và chọn module app, sau đó click vào tab Dependencies.

Tại đây, nhấn vào button có dấu +
và chọn mục Library Dependency và tìm kiếm com.android.support:cardview
, sau đó nhấn OK để kết thúc. Nếu import thư viện theo cách này thì Android Studio sẽ import thư viện mới nhất (ở trên là lib này sử dụng cho API 25 hay Android 7.0 Nougat). Nhanh hơn có thể mở file build.gradle (Module app) và dán dòng dưới đây vào trong dependencies.
compile 'com.android.support:cardview-v7:24.2.1'

Vậy là bây giờ, có thể sử dụng CardView
giống như Button
hay TextView
.
Ví dụ sử dụng CardView
Thực hiện lại ví dụ đã làm trong bài Sử Dụng RecyclerView trong Android nhưng ở bài viết này sẽ thiết kế dòng có sử dụng thêm CardView
- hiển thị danh sách các bài hát Karaoke.
Cũng giống như CardView
, đối với RecyclerView
phải cài đặt thư viện trong dependencies với dòng dưới đây:
compile 'com.android.support:recyclerview-v7:24.2.1'
Và đây là toàn bộ file build.gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.2"
defaultConfig {
applicationId "com.eitguide.cardviewdemo"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:cardview-v7:24.2.1'
compile 'com.android.support:recyclerview-v7:24.2.1'
}
Bước 1: tạo model để chứa data
Lớp Song
đại diện cho 1 bài hát gồm các thông tin:
mCode
: mã số bài hát.mTitle
: tên bài hát.mLyric
: lời bài hát.mAstist
: tên ca sĩ.
File Song.java
package com.eitguide.cardviewdemo;
/**
* Created by nguyennghia on 11/15/16.
*/
public class Song {
private String mCode;
private String mTitle;
private String mLyric;
private String mArtist;
public Song() {
}
public Song(String code, String title, String lyric, String artist) {
this.mCode = code;
this.mTitle = title;
this.mLyric = lyric;
this.mArtist = artist;
}
public String getCode() {
return mCode;
}
public String getTitle() {
return mTitle;
}
public String getLyric() {
return mLyric;
}
public String getArtist() {
return mArtist;
}
public void setCode(String code) {
this.mCode = code;
}
public void setTitle(String title) {
this.mTitle = title;
}
public void setLyric(String lyric) {
this.mLyric = lyric;
}
public void setArtist(String artist) {
this.mArtist = artist;
}
}
Bước 2: thêm RecyclerView vào main_activity.xml
File main_activity.java
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="com.eitguide.cardviewdemo.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/rv_songs"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Bước 3: tạo giao diện cho 1 dòng
<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="3dp"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
card_view:cardCornerRadius="8dp"
card_view:cardElevation="8dp">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="3dp"
android:paddingLeft="6dp"
android:paddingRight="6dp"
android:paddingTop="3dp">
<FrameLayout
android:id="@+id/fl_code"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_centerVertical="true">
<TextView
android:id="@+id/tv_code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#19b395"
android:textSize="18dp" />
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="8dp"
android:layout_toRightOf="@+id/fl_code"
android:orientation="vertical">
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:textColor="#2c3e50"
android:textSize="16dp"
android:textStyle="bold" />
<TextView
android:id="@+id/tv_lyric"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:textColor="#34495e"
android:textSize="14dp" />
<TextView
android:id="@+id/tv_artist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#7f8c8d"
android:textSize="14dp" />
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
Thay vì sử dụng các ViewGroup
khác, ở đây sử dụng CardView
.
Bước 4: tạo custom Adapter và bind dữ liệu cho từng dòng trong Adapter
package com.eitguide.cardviewdemo;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
/**
* Created by nguyennghia on 11/15/16.
*/
public class SongAdapter extends RecyclerView.Adapter<SongAdapter.SongViewHolder> {
private static final String TAG = "SongAdapter";
private List<Song> mSongs;
private Context mContext;
private LayoutInflater mLayoutInflater;
public SongAdapter(Context context, List<Song> datas) {
mContext = context;
mSongs = datas;
mLayoutInflater = LayoutInflater.from(context);
}
@Override
public SongViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//inflate view from row_item_song.xml
View itemView = mLayoutInflater.inflate(R.layout.row_item_song, parent, false);
return new SongViewHolder(itemView);
}
@Override
public void onBindViewHolder(SongViewHolder holder, int position) {
//get song in mSong via position
Song song = mSongs.get(position);
//bind data to viewholder
holder.tvCode.setText(song.getCode());
holder.tvTitle.setText(song.getTitle());
holder.tvLyric.setText(song.getLyric());
holder.tvArtist.setText(song.getArtist());
}
@Override
public int getItemCount() {
return mSongs.size();
}
class SongViewHolder extends RecyclerView.ViewHolder {
private TextView tvCode;
private TextView tvTitle;
private TextView tvLyric;
private TextView tvArtist;
public SongViewHolder(View itemView) {
super(itemView);
tvCode = (TextView) itemView.findViewById(R.id.tv_code);
tvTitle = (TextView) itemView.findViewById(R.id.tv_title);
tvLyric = (TextView) itemView.findViewById(R.id.tv_lyric);
tvArtist = (TextView) itemView.findViewById(R.id.tv_artist);
}
}
}
Bước 5: cài đặt RecyclerView trong MainActivity.java
Không giống như ListView
chỉ cần đặt Adapter cho ListView
, đối với RecyclerView
phải đặt 2 thành phần bắt buộc dưới đây:
- Đặt Adapter cho
RecyclerView
, sử dụng phương thứcsetAdapter()
. - Đặt layout manager để chỉ định layout các item như thế nào (vertical, horizontal, grid, staggered grid) bằng cách sử dụng phương thức
setLayoutManager()
.
File MainActivity.java
package com.eitguide.cardviewdemo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView rvSongs;
private SongAdapter mSongAdapter;
private List<Song> mSongs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rvSongs = (RecyclerView)findViewById(R.id.rv_songs);
//create song data
mSongs = new ArrayList<>();
mSongs.add(new Song("60696", "NẾU EM CÒN TỒN TẠI", "Khi anh bắt đầu 1 tình yêu Là lúc anh tự thay", "Trịnh Đình Quang"));
mSongs.add(new Song("60701", "NGỐC", "Có rất nhiều những câu chuyện Em dấu riêng mình em biết", "Khắc Việt"));
mSongs.add(new Song("60650", "HÃY TIN ANH LẦN NỮA", "Dẫu cho ta đã sai khi ở bên nhau Cô yêu thương", "Thiên Dũng"));
mSongs.add(new Song("60610", "CHUỖI NGÀY VẮNG EM", "Từ khi em bước ra đi cõi lòng anh ngập tràng bao", "Duy Cường"));
mSongs.add(new Song("60656", "KHI NGƯỜI MÌNH YÊU KHÓC", "Nước mắt em đang rơi trên những ngón tay Nước mắt em", "Phạm Mạnh Quỳnh"));
mSongs.add(new Song("60685", "MỞ", "Anh mơ gặp em anh mơ được ôm anh mơ được gần", "Trịnh Thăng Bình"));
mSongs.add(new Song("60752", "TÌNH YÊU CHẮP VÁ", "Muốn đi xa nơi yêu thương mình từng có Để không nghe", "Mr. Siro"));
mSongs.add(new Song("60608", "CHỜ NGÀY MƯA TAN", "1 ngày mưa và em khuất xa nơi anh bóng dáng cứ", "Trung Đức"));
mSongs.add(new Song("60603", "CÂU HỎI EM CHƯA TRẢ LỜI", "Cần nơi em 1 lời giải thích thật lòng Đừng lặng im", "Yuki Huy Nam"));
mSongs.add(new Song("60720", "QUA ĐI LẶNG LẼ", "Đôi khi đến với nhau yêu thương chẳng được lâu nhưng khi", "Phan Mạnh Quỳnh"));
mSongs.add(new Song("60856", "QUÊN ANH LÀ ĐIỀU EM KHÔNG THỂ - REMIX", "Cần thêm bao lâu để em quên đi niềm đâu Cần thêm", "Thiện Ngôn"));
mSongAdapter = new SongAdapter(this, mSongs);
rvSongs.setAdapter(mSongAdapter);
//RecyclerView scroll vertical
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
rvSongs.setLayoutManager(linearLayoutManager);
}
}

1 số thuộc tính thường dùng với CardView
Khảo sát đoạn mã thiết kế dòng ở trên:
<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:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="3dp"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:background="#2ecc71"
card_view:cardCornerRadius="8dp"
card_view:cardBackgroundColor="#2ecc71"
card_view:cardElevation="8dp">
Có 3 thuộc tính cần quan tâm đó là:
card_view:cardCornerRadius
: xác định mức độ bo tròn củaCardView
.card_view:cardBackgroundColor
:CardView
không đặt màu nền bằng thuộc tínhbackground
như nhữngView
khác mà phải thông qua thuộc tính này.card_view:cardElevation
: xác định "mức độ đổ bóng" choCardView
.
Ngoài cài đặt những thuộc tính này trong XML, cũng có thể cài đặt trong mã Java như sau:
CardView card = ...
card.setCardBackgroundColor(Color.parseColor("#E6E6E6"));
card.setMaxCardElevation(0.0);
card.setRadius(5.0);