2016-07-07 279 views
0

我在drawable文件夹中有frame(frame1.png ... frame5.png),我在drawable文件夹内创建了一个bg_animation.xml文件。如何在Android Studio中为背景添加动画效果?

<?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: 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

回答

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>