how to add animation to textView drawable

半腔热情 提交于 2019-11-28 12:01:50
Sanders

if you set the drawable in the XML, you won't be able to access it like you can with an ImageView's getDrawable(). Instead, omit it from your XML and do it in your 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();

Provided your drawable ic_launcher can be animated like an AnimationDrawable, this should start the animation. Call d.stop() to cease animation.

To make simple animations like rotation you can do something like this:

Assume @drawable/ic_launcher is a drawable you want to animate.
Define some_drawable.xml with the appropriate values:

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

Assign this drawable as a compound one to your 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"
    >

To start animation:

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();
}

10000 can be find in source of Drawable

/**
 * Retrieve the current level.
 *
 * @return int Current level, from 0 (minimum) to 10000 (maximum).
 */
public final @IntRange(from=0,to=10000) int getLevel() {
    return mLevel;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!