Kata03 RecyclerView and Cards - mitchwongho/GDS-Material-Kata GitHub Wiki
Introduction
RecyclerView
and CardView
are two widgets that were added in Android Lollipop 🍭to provide a more advance and flexible alternative to ListView
.
Goal
The goal of this kata is to apply a RecyclerView
to our main layout and add cards to that RecyclerView
.
[Source reference]
Exercise
Begin by adding a RecyclerView
to res/layout/activity_main.xml
between our header Toolbar
and footer Toolbar
:
...
<android.support.v7.widget.RecyclerView
android:id="@+id/main_recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:paddingTop="@dimen/normal_padding"
android:paddingBottom="@dimen/normal_padding"
android:clipToPadding="false"
app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
...
<!-- Header Toolbar -->
...
<!-- Footer Toolbar -->
...
Next, create simple_cardview.xml
, a CardView
layout using the compatibility support version android.support.v7.widget.CardView
in res/layout/
:
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="@dimen/simple_card_height"
android:layout_marginLeft="@dimen/large_padding"
android:layout_marginRight="@dimen/large_padding"
android:layout_marginTop="@dimen/normal_padding"
android:layout_marginBottom="@dimen/normal_padding"
card_view:contentPadding="@dimen/normal_padding"
android:clickable="true"
android:foreground="?attr/selectableItemBackground">
<TextView
android:id="@+id/card_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/AppTheme.TextAppearance.Medium"
tools:text="Title text"/>
</android.support.v7.widget.CardView>
Finally, create a RecyclerView.Adapter
that can apply your simple_cardview.xml
layout to the RecyclerView
. The RecyclerView
then can be initialised in your MainActivity
:
protected void onCreate(Bundle savedInstanceState) {
...
// Initialise RecyclerView and apply String-array
final String[] dow = getResources().getStringArray(R.array.days_of_week);
final SimpleAdapter adapter = new SimpleAdapter(dow);
final RecyclerView recyclerView = (RecyclerView)findViewById(R.id.main_recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
...
}