Android CardView with a custom shadow color-ThrowExceptions

Exception or error:

Is it possible to change the color of the shadow around the CardView? Mainly used to mark selected the card as it were lighted on?

Should be valid on L and pre-L devices.

How to solve:

CardView shadow colors are defined in the resources of the CardView library. You can override them by redefining the resource value in your own project but you can not change them dynamically by code.

Edit: overriding the resource value only affects pre-Lollipop devices. On Lollipop and above, CardView always uses the native shadow implementation whose color cannot be changed.

###

Update: Check my modification.


Here’s a workaround:

Copy the source code of CardView. Then create your own Android Library Module and use this module instead of support library. After these, comment or remove code in CardView like below:

static {
//        if (Build.VERSION.SDK_INT >= 21) {
//            IMPL = new CardViewApi21Impl();
//        } else
            if (Build.VERSION.SDK_INT >= 17) {
            IMPL = new CardViewApi17Impl();
        } else {
            IMPL = new CardViewBaseImpl();
        }
        IMPL.initStatic();
    }

That is, you will use compat-version CardViewApi17Impl even when api is 21 or higher. Then, you can define your own cardview_shadow_start_color and cardview_shadow_end_color to override those in class RoundRectDrawableWithShadow. Furthermore, you can make that more customizable.

Hope can help someone.

###

I’ve used a small trick. One CardView is put behind another one. Both are the same, difference is card_view:cardElevation="10dp" for background one, and card_view:cardElevation="2dp" for faced one. The subtraction of elevation provides how long is your shadow, and color of the second CardView gonna be color of the shadow for first one.

Example:

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/view_click_basement"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="2dp"
    card_view:cardCornerRadius="5dp"
    card_view:cardBackgroundColor="@color/colorNewGreen"
    card_view:cardElevation="10dp"
    card_view:cardUseCompatPadding="true">

    <android.support.v7.widget.CardView
        android:id="@+id/view_click"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="2dp"
        card_view:cardCornerRadius="5dp"
        card_view:cardElevation="2dp"
        card_view:cardUseCompatPadding="true">

###

Try this :-

android:outlineSpotShadowColor=”@color/”
android:outlineAmbientShadowColor=”@color/”

Leave a Reply

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