Android CardView with a custom shadow color

本小妞迷上赌 提交于 2019-12-03 10:51:47

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.

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!