Skip to content
Advertisement

How to create programmatically CardView

I’m developing an Android app in Java & Android Studio.

I want to create in activity a CardView programmatically. I want to set the following properties to the CardView:

layout_width="wrap_content"
layout_row="0"
layout_column="1"
layout_gravity="fill"
layout_margin="8dp"
layout_columnWeight="1"
layout_rowWeight="1"
cardCornerRadius="8dp"
cardElevation="8dp"

The card should be created in a GridLayout

CardView cardView = new CardView(getActivity());

Advertisement

Answer

Here is an example. you can add other parameters as well:

cardview = new CardView(context);

        layoutparams = new LayoutParams(
                LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT
        );

        cardview.setLayoutParams(layoutparams);
        cardview.setRadius(15);
        cardview.setPadding(25, 25, 25, 25);
        cardview.setCardBackgroundColor(Color.MAGENTA);
        cardview.setMaxCardElevation(30);
        cardview.setMaxCardElevation(6);

relativeLayout.addView(cardview);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement