我在drawable文件夹中有框架(frame1.png ... frame5.png),我在drawable文件夹中创建了一个bg_animation.xml文件。
<?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>
我尝试使用this code,看起来像这样:
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();
}
}
XML中有一个ImageView,它看起来像这样:
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/backg" />
</RelativeLayout>
当我在手机中启动应用程序(4.4.2)时,它会因此错误崩溃:
java.lang.RuntimeException:无法启动活动 ComponentInfo {hu.media.smk.test / hu.media.smk.test.MainActivity}: java.lang.ClassCastException: android.graphics.drawable.StateListDrawable无法强制转换为 android.graphics.drawable.AnimationDrawable
答案 0 :(得分:0)
只需删除选择器
即可使用此
<?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>
而不是
<?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>