layout_margin in CardView is not working properly

Eric Cochran picture Eric Cochran · Jul 4, 2014 · Viewed 21.9k times · Source

I am playing with the new CardView, but the margins don't seem to be applying.

<?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:id="@+id/card_view"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="18dp"
android:layout_marginLeft="18dp"
android:layout_marginRight="18dp"
card_view:cardCornerRadius="4dp"
card_view:cardBackgroundColor="#FFA"
card_view:layout_margind="4dp">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

<TextView
    android:id="@+id/info_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"/>

</LinearLayout>

</android.support.v7.widget.CardView>

By the way, I'm using it in a Fragment that is in a ViewPager. The card extends the entire width of the screen (match_parent) even though I am using android:layout_marginLeft="18dp" and android:layout_marginRight="18dp" on the CardView.

Any ideas what I might be doing wrong?

Answer

zonda picture zonda · Aug 29, 2014

If you use RecyclerView to add CardView, android:layout_margin should be sufficient.

But using ListView to add CardView, you might do this:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="11dp"
    android:layout_marginRight="11dp"
    android:layout_marginTop="11dp">
       (other layout ...)
</android.support.v7.widget.CardView>

</FrameLayout>

But it is usually not the optimal one.