Drawable as Background for CardView
I know this is an old question, but I have a simple solution - just make the first child of your CardView an ImageView and specify the scale type to fitXY. You can get rid of the extra CardView padding by setting cardElevation and cardMaxElevation to 0dp
:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="200dp"
app:cardCornerRadius="4dp"
app:cardElevation="0dp"
app:cardMaxElevation="0dp">
<ImageView
android:src="@drawable/your_background"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"/>
<... your layout
.../>
</android.support.v7.widget.CardView>
for drawable or color just use:
cvSellerShopp.setBackgroundResource(R.drawable.ic_action_add_image);
for color use:
cvSellerShopp.setCardBackgroundColor(R.color.colorPrimary);
but this one does not produce the intended results
Make Cardview will host one viewgroup for eg relative layout in this case and then simply set any background to relative layout.
<?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/list_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
card_view:cardCornerRadius="4dp"
card_view:cardUseCompatPadding="true">
<RelativeLayout
android:id="@+id/list_container_bg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical">
<!--Add cardview contents-->
</RelativeLayout>
</android.support.v7.widget.CardView>
I got this working by adding a linearlayout in the cardview and then setting cardPreventCornerOverlap to false in the cardview.
<android.support.v7.widget.CardView
android:id="@+id/result_cv"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_margin="4dp"
app:cardCornerRadius="16dp"
app:cardElevation="8dp"
app:cardPreventCornerOverlap="false"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/gradient"
android:gravity="center"
>
<!-- your views -->
</LinearLayout>
</android.support.v7.widget.CardView>
The command I used was:
cardView.setBackgroundResource(R.drawable.card_view_bg);
where card_view_bg is a custom XML resource file.
If you have some layouts inside the card view and these layouts are overlapping with the margins of the card view then you might need a separate custom background resource file for the layouts like the one I used for the card view background itself.