Search code examples
androidanimationandroid-animationnine-patch

How to animate between two different 9-patch images?


How do I animate between two 9-patched image files? I have two 9-patched image files that are different shapes and I want to animate over time from one image to the next. I know of a way using drawables that I thought would apply, however, I am receiving a casting error

android.graphics.drawable.NinePatchDrawable cannot be cast to android.graphics.drawable.TransitionDrawable

Here is my implementation. I created a drawable file referencing my two 9-patch images.

<?xml version="1.0" encoding="UTF-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/bg_drawer_blue" />
    <item android:drawable="@drawable/bg_drawer_white" />
</transition>

I then tried to do an animation

TransitionDrawable transition = (TransitionDrawable) mAnimateBgView.getBackground();
transition.startTransition(10000);

I have also tried

TransitionDrawable td = new TransitionDrawable(new Drawable[] {
     getResources().getDrawable(R.drawable.bg_drawer_blue),
     getResources().getDrawable(R.drawable.bg_drawer_white)
});
d.startTransition(1000);

There were no results. The animation did not work.


Solution

  • For other running into this issue, the reason is because the xml drawable was not set as background.

    Adding the line below resolved the casting issue.

    mAnimateBgView.setBackground(getResources().getDrawable(R.drawable.anim_bg));