Getting Started With Card View
If you are interested in building an Android app that makes use of lists to display data, Android Lollipop features new widget to make your life beutiful, CardView. Using this widget, it is very easy to give your app a look and feel that conforms to the guidelines mentioned in Google's material design specification.
Support Older Versions
At the time of writing, near about 71% of Android devices run Android Lollipop. However, thanks to the v7 Support Library, you can use the RecyclerView and CardView widgets on devices that run older versions of Android by adding the following lines to the dependencies section in your project's build.grade file:
compile 'com.android.support:cardview-v7:26.0.0-alpha1'
compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
Creating a CardView
A CardView is a ViewGroup. Like any other ViewGroup, it can be added to your Activity or Fragment using a layout XML file.
To create an empty CardView, you would have to add the following code to your layout XML as shown in the following snippet:
<android.support.v7.widget.CardView
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>
As a more realistic example, let us now create a LinearLayout and place a CardView inside it. The CardView could represent, for example, a person and contain the following:
a TextView to display the name of the person
a TextView to display the person's age
an ImageView to display the person's photo
This is what the XML would look like:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:padding="16dp"
>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/cv"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/person_photo"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="16dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/person_name"
android:layout_toRightOf="@+id/person_photo"
android:layout_alignParentTop="true"
android:textSize="30sp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/person_age"
android:layout_toRightOf="@+id/person_photo"
android:layout_below="@+id/person_name"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
If this XML is used as the layout of an Activity, with the TextView and ImageView fields are set to meaningful
values, then this is how it would render on an Android device:
Comments
Post a Comment