android – How to set CardView's elevation programmatically?-ThrowExceptions

Exception or error:

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.

How to solve:

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 !!

###

use cardview.setMaxCardElevation(8); instead

###

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.

###

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);

###

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.

Leave a Reply

Your email address will not be published. Required fields are marked *