Shahin Ghasemi
Shahin Ghasemi

Reputation: 1759

How to set CardView's elevation programmatically?

Hello I just want to set the elevation of cardview programmatically but seems it does not work , here's my Code :

CardView cardView = new CardView(this);
    LinearLayout.LayoutParams params =
            new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);
    cardView.setLayoutParams(params);
    LinearLayout linearLayout = (LinearLayout)findViewById(R.id.linear);
    cardView.setCardBackgroundColor(Color.WHITE);
    cardView.setCardElevation(1000);
    linearLayout.addView(cardView);

even though setCardEleveation is set to 1000 there is no changes to cardview, what's wrong ? there is some related question out there but i can't got the answer.

Upvotes: 2

Views: 5862

Answers (5)

Akintunde
Akintunde

Reputation: 1

XML property "cardElevation" will achieve this for you, however. Since the Material Design Guideline states that the CardView elevation can only be 8dp, you can as well set this in your XML file once and for all.

Upvotes: -1

Himanshu Kohli
Himanshu Kohli

Reputation: 86

The minimum api is 15 and max is 21

Image of the code

CardView cardView = new CardView(this);
        LinearLayout.LayoutParams params =
                new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,200);
        cardView.setLayoutParams(params);
        LinearLayout linearLayout = (LinearLayout)findViewById(R.id.linear);
        cardView.setCardBackgroundColor(Color.WHITE);
        cardView.setCardElevation(20);
        linearLayout.addView(cardView);

Upvotes: 0

Shahin Ghasemi
Shahin Ghasemi

Reputation: 1759

Ok , i had a tricky problem , my Cardview wrapped its Parent up so there is no space available to show its shadow. finally I added margin to the Cardview and now It works !!

Upvotes: 3

Ircover
Ircover

Reputation: 2446

From elevation depends only views shadow. It is good shown when elevation is about 2, 10, may be 20 and not much more. When you set something like 1000 shadow becomes almost invisible because of great distance (as it is in the real world :) ).

Try to set less elevation.

Upvotes: 0

Oussema Aroua
Oussema Aroua

Reputation: 5339

use cardview.setMaxCardElevation(8); instead

Upvotes: 0

Related Questions