Tutorial Cardview With Recyclerview in Android Studio
Halo semuanya, hari ini saya akan berbagi sedikit tentang cara membuat Cardview dengan Recyclerview di Android Studio. Jadi, output dari tutorial ini adalah program yang memiliki banner dan ada beberapa grid di bawahnya yang memiliki dua kolom.
Jadi, Anda harus menyiapkan satu gambar spanduk dan 10 gambar dengan ukuran persegi. Jika Anda tidak memilikinya, Anda dapat mengunduh gambar di bawah ini dan menyimpannya di folder proyek Drawable Anda.
Download Images
Kemudian kita mulai saja tutorialnya. Pertama tentunya Anda harus membuat project baru di Android Studio dengan tipe aktivitas kosong, lalu masuk ke bagian Module lalu masukkan beberapa library yang dibutuhkandependencies{
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:25.1.1'
compile 'com.android.support:cardview-v7:25.1.1'
compile 'com.android.support:recyclerview-v7:25.1.1'
compile 'com.android.support:design:25.1.1'
compile 'com.github.bumptech.glide:glide:3.7.0'
testCompile 'junit:junit:4.12'
compile 'com.google.android.gms:play-services-appindexing:8.4.0'
}
Jika proses sinkronisasi selesai dan tidak ada masalah, buka bagian colors.xml untuk mengubah warna tampilan.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<color name="viewBg">#f1f5f8</color>
<color name="album_title">#4c4c4c</color>
</resources>
Kemudian buka dimens.xml dan masukkan kode berikut:
<resources>
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
<dimen name="fab_margin">16dp</dimen>
<dimen name="item_offset">10dp</dimen>
<dimen name="detail_backdrop_height">250dp</dimen>
<dimen name="backdrop_title">30dp</dimen>
<dimen name="backdrop_subtitle">18dp</dimen>
<dimen name="card_margin">5dp</dimen>
<dimen name="card_pc_radius">0dp</dimen>
<dimen name="pc_cover_height">160dp</dimen>
<dimen name="pc_title_padding">10dp</dimen>
<dimen name="pc_title">15dp</dimen>
<dimen name="songs_count_padding_bottom">5dp</dimen>
<dimen name="songs_count">12dp</dimen>
<dimen name="ic_pc_overflow_width">20dp</dimen>
<dimen name="ic_pc_overflow_height">30dp</dimen>
<dimen name="ic_pc_overflow_margin_top">10dp</dimen>
</resources>
Buka strings.xml dan masukkan kode berikut:
<resources>
<string name="app_name">Card View</string>
<string name="action_settings">Settings</string>
<string name="action_rate">Rate</string>
<string name="action_share">Share</string>
<string name="backdrop_title">PC Fantastic</string>
<string name="backdrop_subtitle">This Season Top 10 PC</string>
</resources>
Buka menu_movie.xml. (Anda dapat menyesuaikan nama menu Anda) dan masukkan kode berikut
<menu 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"
tools:context="id.ndiappink.cardview.MainActivity">
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
app:showAsAction="never" />
</menu>
Buka styles.xml dan masukkan kode berikut:
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
Sekarang kita pindahkan bagian layout lalu edit content_main.xml dan masukkan kode berikut
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:background="@color/viewBg"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/activity_main">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="false"
android:scrollbars="vertical" />
</RelativeLayout>
Selanjutnya, buat layout baru dan beri nama pc_card.xml dan masukkan kode berikut
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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.support.v7.widget.CardView
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_margin="@dimen/card_margin"
android:elevation="3dp"
card_view:cardCornerRadius="@dimen/card_pc_radius">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/thumbnail"
android:layout_width="match_parent"
android:layout_height="@dimen/pc_cover_height"
android:background="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
android:scaleType="fitXY" />
<TextView
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/thumbnail"
android:paddingLeft="@dimen/pc_title_padding"
android:paddingRight="@dimen/pc_title_padding"
android:paddingTop="@dimen/pc_title_padding"
android:textColor="@color/album_title"
android:textSize="@dimen/pc_title" />
<TextView
android:id="@+id/rating"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:paddingBottom="@dimen/songs_count_padding_bottom"
android:paddingLeft="@dimen/pc_title_padding"
android:paddingRight="@dimen/pc_title_padding"
android:textSize="@dimen/songs_count" />
<ImageView
android:id="@+id/overflow"
android:layout_width="@dimen/ic_pc_overflow_width"
android:layout_height="@dimen/ic_pc_overflow_height"
android:layout_alignParentRight="true"
android:layout_below="@id/thumbnail"
android:layout_marginTop="@dimen/ic_pc_overflow_margin_top"
android:scaleType="centerCrop"
android:src="@drawable/ic_dots" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Jika sudah bagus di sini, buka activity_main.xml dan masukkan kode berikut
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="@dimen/detail_backdrop_height"
android:fitsSystemWindows="true"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp"
app:expandedTitleTextAppearance="@android:color/transparent"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/backdrop"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
app:layout_collapseMode="parallax" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="@+id/love_music"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/backdrop_title"
android:textColor="@android:color/white"
android:textSize="@dimen/backdrop_title" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/backdrop_subtitle"
android:textColor="@android:color/white"
android:textSize="@dimen/backdrop_subtitle" />
</LinearLayout>
</RelativeLayout>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main" />
</android.support.design.widget.CoordinatorLayout>
Sekarang kita pindah ke bagian Kelas dan buat kelas baru lalu beri nama PC lalu masukkan kode berikut
public class PC {
private String name;
private int thumbnail;
private int rating;
public PC(String name, int rating, int thumbnail) {
this.name = name;
this.rating = rating;
this.thumbnail = thumbnail;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getThumbnail() {
return thumbnail;
}
public void setThumbnail(int thumbnail) {
this.thumbnail = thumbnail;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
}
Paradise Hotel - Responsive WordPress Hotel Theme
Responsive Paradise Hotel is a WordPress theme suitable for hotels, restaurants, spa and similar. The layout looks beautiful at any size, be it a laptop screen, iPad, iPhone, Android Mobile or tablets.
Get it Now
Buat kelas baru lagi dan beri nama PCAdapter dan masukkan kode berikut:
import android.content.Context;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import java.util.List;
public class PCAdapter extends RecyclerView.Adapter<PCAdapter.MyViewHolder> {
private Context mContext;
private List<PC> PCList;
public PCAdapter(Context mContext, List<PC> PCList) {
this.mContext = mContext;
this.PCList = PCList;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name, rating;
public ImageView thumbnail, overflow;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.name);
rating= (TextView) view.findViewById(R.id.rating);
thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
overflow = (ImageView) view.findViewById(R.id.overflow);
}
}
@Override
public PCAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.pc_card, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(final PCAdapter.MyViewHolder holder, int position) {
PC movie = PCList.get(position);
holder.name.setText(movie.getName());
holder.rating.setText("Rating: "+String.valueOf( movie.getRating()));
Glide.with(mContext).load(movie.getThumbnail()).into(holder.thumbnail);
holder.overflow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showPopupMenu(holder.overflow);
}
});
}
@Override
public int getItemCount() {
return PCList.size();
}
private void showPopupMenu(View view) {
// inflate menu
PopupMenu popup = new PopupMenu(mContext, view);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_movie, popup.getMenu());
popup.setOnMenuItemClickListener(new MyMenuItemClickListener());
popup.show();
}
class MyMenuItemClickListener implements PopupMenu.OnMenuItemClickListener {
public MyMenuItemClickListener() {
}
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_rate:
Toast.makeText(mContext, "Rate", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_share:
Toast.makeText(mContext, "Share", Toast.LENGTH_SHORT).show();
return true;
default:
}
return false;
}
}
}
MORE ARTICLE
Create Installer Project Netbeans
Buka MainActivity dan masukkan kode berikut
import android.content.res.Resources;
import android.graphics.Rect;
import android.net.Uri;
import android.support.design.widget.AppBarLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private PCAdapter adapter;
private List<PC> PCList;
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initCollapsingToolbar();
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
PCList = new ArrayList<>();
adapter = new PCAdapter(this, PCList);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
prepareAlbums();
try {
Glide.with(this).load(R.drawable.cover).into((ImageView) findViewById(R.id.backdrop));
} catch (Exception e) {
e.printStackTrace();
}
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void initCollapsingToolbar() {
final CollapsingToolbarLayout collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
collapsingToolbar.setTitle(" ");
AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
appBarLayout.setExpanded(true);
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
collapsingToolbar.setTitle(getString(R.string.app_name));
isShow = true;
} else if (isShow) {
collapsingToolbar.setTitle(" ");
isShow = false;
}
}
});
}
private void prepareAlbums() {
int[] posters = new int[]{
R.drawable.pc1,
R.drawable.pc2,
R.drawable.pc3,
R.drawable.pc4,
R.drawable.pc5,
R.drawable.pc6,
R.drawable.pc7,
R.drawable.pc8,
R.drawable.pc9,
R.drawable.pc10,};
PC a = new PC("PC 1", 3, posters[0]);
PCList.add(a);
a = new PC("PC 2", 5, posters[1]);
PCList.add(a);
a = new PC("PC 3", 11, posters[2]);
PCList.add(a);
a = new PC("PC 4", 12, posters[3]);
PCList.add(a);
a = new PC("PC 5", 14, posters[4]);
PCList.add(a);
a = new PC("PC 6", 1, posters[5]);
PCList.add(a);
a = new PC("PC 7", 11, posters[6]);
PCList.add(a);
a = new PC("PC 8", 14, posters[7]);
PCList.add(a);
a = new PC("PC 9", 11, posters[8]);
PCList.add(a);
a = new PC("PC 10", 11, posters[9]);
PCList.add(a);
adapter.notifyDataSetChanged();
}
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page")
.setUrl(Uri.parse(""))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
@Override
public void onStart() {
super.onStart();
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
@Override
public void onStop() {
super.onStop();
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {
private int spanCount;
private int spacing;
private boolean includeEdge;
public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
this.spanCount = spanCount;
this.spacing = spacing;
this.includeEdge = includeEdge;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view);
int column = position % spanCount;
if (includeEdge) {
outRect.left = spacing - column * spacing / spanCount;
outRect.right = (column + 1) * spacing / spanCount;
if (position < spanCount) {
outRect.top = spacing;
}
outRect.bottom = spacing;
} else {
outRect.left = column * spacing / spanCount;
outRect.right = spacing - (column + 1) * spacing / spanCount;
if (position >= spanCount) {
outRect.top = spacing;
}
}
}
}
private int dpToPx(int dp) {
Resources r = getResources();
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}
}
Dan terakhir ganti AndroidManifest.xml dengan kode berikut
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="id.ndiappink.cardview">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
</application>
</manifest>
Setelah selesai dan tidak ada kesalahan, program siap dijalankan