I'm using android:paddingLeft
and android:paddingTop
to set the padding for the new CardView
widget but it doesn't work.
I can set the margin for all the controls inside the CardView
as a workaround but that's a pain if there are too many controls.
How to set padding for the new cardview widget?
<android.support.v7.widget.CardView
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="200dp"
android:paddingLeft="20dp"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="20dp"
android:paddingBottom="@dimen/activity_vertical_margin"
card_view:cardCornerRadius="2dp">
<TextView
android:id="@+id/info_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!"/>
</android.support.v7.widget.CardView>
CardView prior to L-preview uses
RoundRectDrawableWithShadow
to draw its background, which overridesDrawable.getPadding()
to add shadow padding. The view background gets set via code after inflation, which overrides any padding specified in XML.You have two options:
View.setPadding()
and be careful to adjust for the shadows (but only prior to L-preview!).The latter option is safest.
CardView should handle this using the
contentPadding
attributes it comes with:This is what worked for me - putting every item in a frame layout
Double check that card_view is "http://schemas.android.com/apk/res-auto" and not tools, and also set negative margins on the frame view to maintain shadows - works fine.
If you want to use CardView padding on pre-L devices, and have it look the same on Lollipop+ devices, then you will need to use
setUseCompatPadding(true)
, or the XML variantcardUseCompatPadding="true"
.This is because "CardView adds additional padding to draw shadows on platforms before L."[1] So, the default implementation has the different API versions looking different and views may not line up properly. So, the easiest way to fix that issue is the ways stated above, or use margins instead.
Example Code
Sources
[1] CardView.setUseCompatPadding(boolean)
[2] android.support.v7.cardview:cardUseCompatPadding