Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a more natural CardView alpha animation?

I have a normal CardView:

<androidx.cardview.widget.CardView
    android:id="@+id/cardView"
    android:layout_width="256dp"
    android:layout_height="64dp"
    app:cardElevation="4dp" />

Then I animate its alpha:

cardView.animate().alpha(1f).setDuration(3000).start()

I get:

enter image description here

The card background first turns grey then white. If time is short, this look like a blink. It seems this only happens on a white background.

This is what I want (I create it in the Adobe XD):

enter image description here

How can I achieve a similar effect?

like image 682
Dewey Reed Avatar asked Nov 20 '25 23:11

Dewey Reed


2 Answers

The grey you are seeing is the shadow of your CardView.

You can add the CardView inside another view and animate that view instead, for example:

<RelativeLayout
    android:id="@+id/animateThis"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView"
        android:layout_width="256dp"
        android:layout_height="64dp"
        app:cardElevation="4dp" />

</RelativeLayout>

Then animate the RelativeLayout instead:

animateThis.animate().alpha(1f).setDuration(3000).start()
like image 115
HB. Avatar answered Nov 22 '25 12:11

HB.


Just to share a different approach. I hope it may help others.

I have created an animation that changes alpha and elevation sequentially, to avoid showing the shadow while animating alpha.

For fade in I use:

<set android:ordering="sequentially">
        <objectAnimator
            android:duration="300"
            android:propertyName="alpha"
            android:valueTo="1"
            android:valueType="floatType" />
        <objectAnimator
            android:duration="300"
            android:propertyName="cardElevation"
            android:valueTo="12dp"
            android:valueType="floatType" />
    </set>

For fade out I use:

<set android:ordering="sequentially">
        <objectAnimator
            android:duration="300"
            android:propertyName="cardElevation"
            android:valueTo="0dp"
            android:valueType="floatType" />
        <objectAnimator
            android:duration="300"
            android:propertyName="alpha"
            android:valueTo="0"
            android:valueType="floatType" />
    </set>
like image 22
Vera Rivotti Avatar answered Nov 22 '25 14:11

Vera Rivotti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!