Android rotate drawable in button

Viewed 401

Hello I have add a drawable in a button :

Drawable image = null;
image = getActivity().getDrawable(R.drawable.ic_spinner);
int h = image.getIntrinsicHeight();
int w = image.getIntrinsicWidth();
image.setBounds( 0, 0, w, h );
button.setCompoundDrawables( null, null, image,  null);

I Want to infinite rotate it

I create this in res/anim/rotate.xml

<?xml version="1.0" encoding="utf-8"?>
<rotate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="1000"
    android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:pivotY="50%"
    android:repeatCount="infinite" />

I don't found solution for call it and assign to drawable in my button

Do you have an idea ?

Thanks for your help

1 Answers

You can create a layer-list which contains animation with a drawable.

ic_refresh_rotate.xml

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

Now set the drawable as compound drawable for the Button or TextView.

<androidx.appcompat.widget.AppCompatTextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:textSize="16sp"
    app:drawableLeftCompat="@drawable/ic_refresh_rotate" />

Finally, in your java code, try to start the animation like the following:

Drawable[] compoundDrawables = textView.getCompoundDrawables();
for (Drawable drawable : compoundDrawables) {
    if (drawable == null) continue;
    ObjectAnimator anim = ObjectAnimator.ofInt(drawable, "level", 0, 10000);
    anim.setDuration(1000);
    anim.setRepeatCount(Animation.INFINITE);
    anim.setInterpolator(new LinearInterpolator());
    anim.start();
}

Result:

Related