如何将动画添加到TextView的可绘制对象

18

我在我的xml文件中使用了以下代码行来在textView中添加图片:android:drawableLeft="@drawable/ic_launcher"

   <TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:drawablePadding="5dp"
    android:gravity="center_vertical"
    android:text="@string/hello_world"
    android:textSize="14sp"
    android:textStyle="bold"
    android:drawableLeft="@drawable/ic_launcher"
    >

</TextView>

现在我想为这个可绘制对象添加动画效果。不知道如何访问该图像。

需要帮助吗? 谢谢提前。


使用setCompoundDrawables,似乎没有复合绘图的getter方法。 - pskink
你能解释得再详细一点吗?我该如何使用这个? - user2494741
使用setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom)方法,将top、right和bottom的Drawable参数传递为null,这样你就只设置了left的Drawable。 - pskink
2个回答

16

如果你在XML中设置可绘制对象,就无法像使用ImageViewgetDrawable()方法那样访问它。相反,将其从XML中省略,在你的Activity/Fragment中进行设置:

TextView tv = (TextView) view.findViewById(R.id.textView1);
AnimationDrawable d = (AnimationDrawable) getResources().getDrawable(R.drawable.ic_launcher);
tv.setCompoundDrawables(d, null, null, null);
d.start();

假设你的可绘制对象ic_launcher可以像AnimationDrawable一样进行动画处理,则应启动动画。调用d.stop()停止动画。


请问您能展示一下您使用的可绘制对象吗?另外,我该如何反转动画? - android developer

11

要制作简单的旋转动画,您可以像这样操作:

假设@drawable/ic_launcher是您想要动画的可绘制对象。
使用适当的值定义some_drawable.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <rotate
            android:drawable="@drawable/ic_launcher"
            android:pivotX="50%"
            android:pivotY="50%"
            android:fromDegrees="0"
            android:toDegrees="180" />
    </item>
</layer-list>

将此可绘制对象分配为复合对象,以应用于您的TextView:

<TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:drawablePadding="5dp"
    android:gravity="center_vertical"
    android:text="@string/hello_world"
    android:textSize="14sp"
    android:textStyle="bold"
    android:drawableLeft="@drawable/some_drawable"
    >

开始动画:

int MAX_LEVEL = 10000;

Drawable[] myTextViewCompoundDrawables = myTextView.getCompoundDrawables();
for(Drawable drawable: myTextViewCompoundDrawables) {

    if(drawable == null)
        continue;

    ObjectAnimator anim = ObjectAnimator.ofInt(drawable, "level", 0, MAX_LEVEL);
    anim.start();
}

1
10000来自哪里? - android developer
2
超过9000! - rtsketo
@androiddeveloper 因为可绘制级别最高可以达到10000。 - MirecXP
@MirecXP 为什么有最大值?这是否有文档记录?我们不能在没有这个最大值的情况下完成吗?毕竟,有些可绘制对象应该永远播放... - android developer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接