首页 > 解决方案 > 如何使用动画旋转图层列表中的项目?

问题描述

我有一个使用图层列表作为其可绘制对象的 ImageView。这是一个显示移动车辆方位的指南针。

我希望能够以编程方式和动画旋转指南针的指针。

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 针罗盘

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

...

标签: androidandroid-animationandroid-drawable

解决方案


我从未见过单个 < item > 标签的动画,所以我认为不可能这样做,因为您只能为 ImageView 本身设置动画,并且还会旋转 compass_no_needle。

您可以做的是使两个 ImageView 重叠,针具有透明背景和小高度(或以某种方式将其置于前景),然后仅使用 ViewPropertyAnimator 或 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(...) 

其中 (...) 是您希望它旋转的浮点值。


推荐阅读