Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set margins in cardview programmatically

here is the code

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

Where ever, from xml its working-

android:layout_marginLeft="100dp"

what can be the reason? am i missing something!

i need margin for elevation of cardview

Thanks

like image 610
Khode_Erfan Avatar asked Mar 22 '15 17:03

Khode_Erfan


2 Answers

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(R.id.text_view);

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

textView.setLayoutParams(layoutParams);
like image 105
paulina_glab Avatar answered Sep 16 '22 19:09

paulina_glab


you can add elevation padding in card view

CardView card = new CardView(this);

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

card.setLayoutParams(params);
card.setContentPadding(2, 1, 2, 1);
card.setMaxCardElevation(5);
card.setCardElevation(9);
like image 31
KDD Avatar answered Sep 18 '22 19:09

KDD