6Geri6 6Geri6 - 4 months ago 49
Android Question

How to animate background in Android Studio?

I have in the drawable folder the frames (frame1.png ... frame5.png) and I created inside the drawable folder a bg_animation.xml file.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<animation-list android:id="@+id/backganimate" android:oneshot="false">
<item android:drawable="@drawable/frame1" android:duration="50" />
<item android:drawable="@drawable/frame2" android:duration="50" />
<item android:drawable="@drawable/frame3" android:duration="50" />
<item android:drawable="@drawable/frame4" android:duration="50" />
<item android:drawable="@drawable/frame5" android:duration="50" />
</animation-list>
</selector>


I tried to use this code and it looks like this:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ImageView img = (ImageView)findViewById(R.id.backg);
img.setBackgroundResource(R.drawable.bg_animation);
AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground();
frameAnimation.start();
}
}


There is an ImageView in the XML, it looks like this:

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/backg" />
</RelativeLayout>


When I launch the app in my phone (4.4.2), it crashes with this error:


java.lang.RuntimeException: Unable to start activity
ComponentInfo{hu.media.smk.test/hu.media.smk.test.MainActivity}:
java.lang.ClassCastException:
android.graphics.drawable.StateListDrawable cannot be cast to
android.graphics.drawable.AnimationDrawable

Answer

Just remove the selector

Use this

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/backganimate" android:oneshot="false">
    <item android:drawable="@drawable/frame1" android:duration="50" />
    <item android:drawable="@drawable/frame2" android:duration="50" />
    <item android:drawable="@drawable/frame3" android:duration="50" />
    <item android:drawable="@drawable/frame4" android:duration="50" />
    <item android:drawable="@drawable/frame5" android:duration="50" />
</animation-list>

instead of

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<animation-list android:id="@+id/backganimate" android:oneshot="false">
    <item android:drawable="@drawable/frame1" android:duration="50" />
    <item android:drawable="@drawable/frame2" android:duration="50" />
    <item android:drawable="@drawable/frame3" android:duration="50" />
    <item android:drawable="@drawable/frame4" android:duration="50" />
    <item android:drawable="@drawable/frame5" android:duration="50" />
</animation-list>
</selector>
Comments