Make ImageView fit width of CardView

Dan picture Dan · Dec 10, 2014 · Viewed 80.3k times · Source

I have a CardView with rounded corners, I want to have an ImageView at the top like shown in the example taken from the material design guidelines below.

components_cards8.png

<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
     android:id="@+id/card_view"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     card_view:cardCornerRadius="4dp">

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

Then inside the CardView I have this ImageView

<ImageView
    android:id="@+id/imageView"
    android:layout_width="fill_parent"
    android:layout_height="150dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:scaleType="centerCrop"
    android:src="@drawable/default_cover" />

If I have the card_view:cardCornerRadius set to 0dp then the ImageView fits the card like how I want it to.

image_1

However, the material design guidelines state that cards should have rounded corners, and not square corners.

The problem I have is when I set the card_view:cardCornerRadius to something other than 0dp, e.g. 4dp, then the following happens:

image_2

As can be seen, the ImageView does not fit into the CardView.

My question is, how can I make this ImageView fit to the layout of the CardView when it has rounded corners.

Answer

김준호 picture 김준호 · Dec 14, 2014

You need to do 2 things :

1) Call setPreventCornerOverlap(false) on your CardView.

2) Put rounded Imageview inside CardView

About rounding your imageview, I had the same problem so I made a library that you can set different radii on each corners. There is one good library(vinc3m1’s RoundedImageView) that supports rounded corners on ImageView, but it only supports the same radii on every corners. But I wanted it to be rounded only top left and top right corners.

Finally I got the result what I wanted like below.

https://github.com/pungrue26/SelectableRoundedImageView

Rounded ImageView inside CardView