Erfanoabdi Erfanoabdi - 9 months ago 1102
Android Question

Set margins in cardview programmatically

here is the code

CardView.LayoutParams layoutParams = new CardView.LayoutParams(
CardView.LayoutParams.WRAP_CONTENT, CardView.LayoutParams.WRAP_CONTENT);
CardView cv = new CardView(this);

Where ever, from xml its working-


what can be the reason? am i missing something!

i need margin for elevation of cardview



If I understand correctly, you are trying to avoid cropping elevation shadow of CardView.

Instead of manipulate margins, try set cardUseCompatPadding to true and if you are changing elevation dynamically, you should call setMaxCardElevation(float) when CardView is initialized. (Both you can set via xml as well as programmatically).

Setting max elevation for CardView let it takes up space for bigger shadow, but it also add this space for lower elevation.

By the way, if you want to set LayoutParams for some view, you need to use these one, which are corresponding to view's parent.

Example: There is a TextView inside LinearLayout.

TextView textView = (TextView) findViewById(;

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);