我得到java.lang.ClassCastException:android.graphics.drawable.AnimationDrawable

时间:2014-11-24 11:38:54

标签: java android animation frame

我收到了java.lang.ClassCastException:android.graphics.drawable.AnimationDrawable

protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_frame_animation);

    // Directory creation and unzip file       
    DirCreation dc = new DirCreation();
    dc.creation();

    showedImage = (ImageView) findViewById(R.id.imageAnimation);
    showedImage.setBackgroundResource(R.drawable.ic_launcher);
    frameAnimation = (AnimationDrawable) showedImage.getBackground();
}

我也使用外部源SD卡作为图像资源...

我已使用此文件文件名过滤器从sd卡获取文件并存储在字符串数组

         FilenameFilter filefilter = new FilenameFilter() 
        {
            public boolean accept(File dir, String name) 
            {
            return (name.endsWith(".jpeg") || 
                    name.endsWith(".jpg") || 
                    name.endsWith(".png") );
            }
        };

        String[] sNamelist = pictureDirectory.list(filefilter);
        if (sNamelist.length == 0)
        {
            Log.d("Activity", "No pictures in directory.");
            return;
        }

        for (String filename : sNamelist) 
        {
            Log.d("Activity", pictureDirectory +  "/" +filename);

            frameAnimation.addFrame(
                    Drawable.createFromPath(pictureDirectory.getPath() +  "/" + filename), 210 );
        }

        return;
    }

图片目录是我的SD卡路径

pictureDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/animation/");

所以,现在我要做的就是将这些图像设置为我的帧动画资源......

1 个答案:

答案 0 :(得分:0)

您需要在XML文件中定义一系列可绘制对象才能使用AnimationDrawable类。示例如下:

 <!-- Animation frames are wheel0.png -- wheel5.png files inside the
 res/drawable/ folder -->
 <animation-list android:id="@+id/selected" android:oneshot="false">
    <item android:drawable="@drawable/wheel0" android:duration="50" />
    <item android:drawable="@drawable/wheel1" android:duration="50" />
    <item android:drawable="@drawable/wheel2" android:duration="50" />
    <item android:drawable="@drawable/wheel3" android:duration="50" />
    <item android:drawable="@drawable/wheel4" android:duration="50" />
    <item android:drawable="@drawable/wheel5" android:duration="50" />
 </animation-list>

正如Amith所建议的那样,showsImage.getBackground();返回一个Drawable对象。