user12345 user12345 - 1 month ago 27
Android Question

How to add a animation in cardview android?

How to add a animation in cardview of android, if i click on cardview i want to show some animation.

This is the xml for cardview which i created for cardview. How to add a animation inside this

<?xml version="1.0" encoding="utf-8"?>
<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/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp"
card_view:cardMaxElevation="6dp"
card_view:contentPadding="5dp"
android:layout_margin="5dp"
>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<ImageView
android:id="@+id/iv_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000"
android:layout_toRightOf="@id/iv_icon"
android:layout_toEndOf="@id/iv_icon"
android:paddingLeft="10dp"
/>
<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#848484"
android:layout_below="@id/app_label"
android:layout_toRightOf="@id/iv_icon"
android:layout_toEndOf="@id/iv_icon"
android:textStyle="italic"
android:paddingLeft="10dp"
/>

</RelativeLayout>
</android.support.v7.widget.CardView>

Answer

Put this piece of code in your cardview and create a animation.xml and call in

android:stateListAnimator="@anim/animation"

android:foreground="?attr/selectableItemBackground"
        android:stateListAnimator="@anim/animation"
        android:clickable="true"

animation.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- animate the translationZ property of a view when pressed -->
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item
            android:state_enabled="true"
            android:state_pressed="true">
            <set>
                <objectAnimator
                    android:duration="@android:integer/config_shortAnimTime"
                    android:propertyName="translationZ"
                    android:valueTo="6dp"
                    android:valueType="floatType"/>
            </set>
        </item>
        <item>
            <set>
                <objectAnimator
                    android:duration="@android:integer/config_shortAnimTime"
                    android:propertyName="translationZ"
                    android:valueTo="0"
                    android:valueType="floatType"/>
            </set>
        </item>
    </selector>
</set>

Similarly you can use any type of animation