Setting margin programmatically to CardView
In your case you are not specifically interested who is the parent of your CardView
, because the only thing you want to change is the margin. All of the *LayoutParams
classes are direct/indirect children of MarginLayoutParams
, which means you can easily cast to MarginLayoutParams
and perform change on that object:
ViewGroup.MarginLayoutParams layoutParams =
(ViewGroup.MarginLayoutParams) myCardView.getLayoutParams();
layoutParams.setMargins(0, 0, SystemHelper.dpToPx(2), 0);
myCardView.requestLayout();
1) Set the Cardview Parameters for it to be displayed programtically
Setting Carview Parameters
CardView cardView = new CardView(context);
LinearLayout.LayoutParams cardViewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
cardView.setLayoutParams(cardViewParams)
2) Set the Parameters for displaying the Margins around the cardview
Setting Params for Cardview Margins
ViewGroup.MarginLayoutParams cardViewMarginParams = (ViewGroup.MarginLayoutParams) cardView.getLayoutParams();
cardViewMarginParams.setMargins(0, 30, 0, 30);
cardView.requestLayout(); //Dont forget this line