How to rotate an item in a layer-list with animation?

Viewed 146

I have an ImageView that uses a layer-list as its drawable. It's a compass that shows the bearing of a moving vehicle.

I want to be able to rotate the needle of the compass programmatically and with animation.

compass_overlay.xml:

<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/compass_no_needle"/>
    <item android:drawable="@drawable/needle_compass"/>

</layer-list>

compass_no_needle needle_compass

compass_overlay

some_fragment.xml:

...

<ImageView
    android:id="@+id/icon_bearing"
    android:layout_width="wrap_content"
    android:layout_height="80dp"
    android:adjustViewBounds="true"
    app:srcCompat="@drawable/compass_overlay"/>

...
1 Answers

I have never seen animation of single < item > tags so I do not think it is possible to do it like this, since you can only animate the ImageView itself, and that would also rotate the compass_no_needle.

What you could do is make two ImageViews overlap, with the needle having a transparent background and little elevation(or somehow put it to the foreground), and then animate only the needle with ViewPropertyAnimator or ObjectAnimator.

<ImageView
    android:id="@+id/compass_no_needle"
    android:layout_width="wrap_content"
    android:layout_height="80dp"
    android:adjustViewBounds="true"
    app:srcCompat="@drawable/compass_no_needle"/>

<ImageView
    android:id="@+id/needle_compass"
    android:layout_width="wrap_content"
    android:layout_height="80dp"
    android:adjustViewBounds="true"
    android:elevation="1dp"
    app:srcCompat="@drawable/needle_compass"/>


val needle = (findViewById<ImageView>(R.id.needle_compass))
needle.animate().rotationBy(...) 

where (...) is the float value you want it rotated by.

Related