RSS

Creating a “Card” UI in Android

10 Mar

card1

What is a Card?

A card is nothing more than a layout or a view with a background drawable. And that drawable can be defined in XML as a layer drawable.

res/drawable/layer_card_background.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
   <item>
      <shape android:shape="rectangle">
         <solid android:color="#CABBBBBB"/>
         <corners android:radius="2dp" />
      </shape>
   </item>

   <item
      android:left="0dp"
      android:right="0dp"
      android:top="0dp"
      android:bottom="2dp">
      <shape android:shape="rectangle">
         <solid android:color="@android:color/white"/>
         <corners android:radius="2dp" />
      </shape>
   </item>
</layer-list>

The first item in the layer-list defines what will be the card’s shadow. The second item in the layer-list is the main content for the card. You can turn any view or layout into a card by setting the background to the layer_card_background drawable.

res/layout/hello_card.xml

<?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:gravity="center"
   android:background="#E0EEEE">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="center"
      android:gravity="center"
      android:layout_margin="15dp"
      android:padding="15dp"
      android:background="@drawable/layer_card_background"
      android:text="Hello Card!\nThis is an example of a card..."/>
</LinearLayout>

Putting Cards in a List

At this point you probably realize that putting cards in a list view isn’t all that difficult. However, there are a few details that you won’t want to overlook…

ListView Setup
In your listview’s XML definition, you need the following attributes set:

 android:divider="@null"
 android:dividerHeight="10dp"
 android:listSelector="@android:color/transparent"
 android:cacheColorHint="@android:color/transparent"
 android:headerDividersEnabled="true"
 android:footerDividersEnabled="true"
Advertisements
 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: