Mark Molina
Mark Molina

Reputation: 5077

Access animation defined in xml StateListDrawable

I have a statelistdrawable for my button like this:

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <rotate
            android:fromDegrees="90"
            android:toDegrees="90"
            android:pivotX="50%"
            android:pivotY="50%"
            android:drawable="@drawable/spinner"
            android:duration="1200"
            android:repeatCount="infinite"/>
    </item>

    <item>
        <rotate
            android:fromDegrees="90"
            android:toDegrees="90"
            android:pivotX="50%"
            android:pivotY="50%"
            android:drawable="@drawable/spinner"
            android:duration="1200"
            android:repeatCount="infinite"/>
    </item>
</selector>

Now my button, which is declared in xml, has this file set as its drawableTop.

Normally i would declare the rotate part in res/anim and I can start the animation with

Animation a = AnimationUtils.loadAnimation(getContext(), R.anim.spinner);
view.startAnimation(a);

But how can I access the Animation if it's inside a state list drawable to make it start? I've tried something like this but now I'm stuck:

StateListDrawable background = (StateListDrawable) mRecommendButton.getBackground();
        Drawable drawable = background.getCurrent();

Which gives me a drawable but not an Animation.

** EDIT **

apparently it returns a RotateDrawable so I chanched my code but it's still not rotating. Im also using getCompoundDrawables() because I'm setting my drawable xml to Top. Just for the record. It does enter the "if statement".

StateListDrawable background = (StateListDrawable) mRecommendButton.getCompoundDrawables()[1];
    Drawable drawable = background.getCurrent();
    if (drawable instanceof RotateDrawable) {
        ((RotateDrawable) drawable).setLevel(500);
    }

Upvotes: 0

Views: 1022

Answers (1)

Mark Molina
Mark Molina

Reputation: 5077

Fixed. Im using a animated-rotate now

<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"
                         android:drawable="@drawable/spinner_black_48"
                         android:pivotX="50%"
                         android:pivotY="50%"
                         android:fromDegrees="0"
                         android:toDegrees="1080"
                         android:interpolator="@android:anim/linear_interpolator"
                         android:repeatCount="infinite"/>

Java:

mRecommendButton = (Button)v.findViewById(R.id.recommended_button);
        StateListDrawable background = (StateListDrawable) mRecommendButton.getCompoundDrawables()[1]; // Drawable set as drawableTop in xml
        Drawable drawable = background.getCurrent();
        if (drawable instanceof Animatable) {
            ((Animatable) drawable).start();
        }

Upvotes: 1

Related Questions