2010-01-25 110 views
13

我有一些自定义类BitmapStorage,没有附加到任何视图或任何 - 实用程序之一。 我有一个包含<动画列表>与动画帧born_animation.xml文件:如何从xml文件加载AnimationDrawable

<animation-list oneshot="true" > 
    <item drawable="@drawable/frame01" /> 
    <item drawable="@drawable/frame02" /> 
</animation-list> 

我想加载从XML文件动画作为使用资源类的AnimationDrawable(所以它会做所有解析为我),提取位图并将它们放到我的自定义存储类中。

的问题,我有:

Resources res = context.getResources(); 
AnimationDrawable drawable = (AnimationDrawable)res.getDrawable(R.drawable.born_animation); 
assertTrue(drawable != null); <= fails! it's null 

跆拳道?有人能解释我吗?代码编译正常。所有资源都已到位。

我尝试另一种方式 - 使用的ImageView做解析(如在开发指南描述)

结果是相同的。它返回null drawable。

任何hinsts将不胜感激,在此先感谢。

+0

请勿将其设置为背景 - 请参阅下面的示例。 – 2010-01-25 23:06:46

回答

6

耶,我找到了原因! :)

这是我的坏:我没有了我的animation.xml文件的正确的格式:

  • 我没有使用Android:命名空间属性(由于某种原因,我决定这不是所需)
  • 我删除了“持续时间”属性中<项目>标签

后,我固定这些东西res.getDrawable()开始返回正确的AnimationDrawable实例。

只好在Resources.NotFoundException更精确的外观和它的getCause()来找出什么是错的:)

26

可绘制

<animation-list xmlns:android="http://schemas.android.com/apk/res/android" 
       android:id="@+id/myprogress" 
       android:oneshot="false"> 
    <item android:drawable="@drawable/progress1" android:duration="150" /> 
    <item android:drawable="@drawable/progress2" android:duration="150" /> 
    <item android:drawable="@drawable/progress3" android:duration="150" /> 
</animation-list> 

代码:

ImageView progress = (ImageView)findViewById(R.id.progress_bar); 
if (progress != null) { 
    progress.setVisibility(View.VISIBLE); 
    AnimationDrawable frameAnimation = (AnimationDrawable)progress.getDrawable(); 
    frameAnimation.setCallback(progress); 
    frameAnimation.setVisible(true, true); 
} 

查看

<ImageView 
    android:id="@+id/progress_bar" 
    android:layout_alignParentRight="true" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:src="@drawable/myprogress" /> 
+0

嗯。谢谢,但这主要是来自开发指南的代码 - 这不是我想要的。实际上创建ImageView是我不需要的东西 - 我试图将其作为解决方法。我不会在任何地方显示它。 如何在没有ImageView的情况下执行此操作?为什么我尝试的第一个变体(使用res.getDrawable())失败? – dimsuz 2010-01-25 23:45:14

+1

另外我不能使用View.findViewById,因为我没有视图 - 正如我所说这是一个实用程序类。 想象一下,我有一个对视图/活动一无所知的库。它不能加载资源吗?:) – dimsuz 2010-01-26 11:43:42

+0

的方式来完成活动一旦完成? – RobinHood 2012-11-30 10:48:00

3

这可以用来从“XML”的目录中加载资源。

Drawable myDrawable; 
Resources res = getResources(); 
try { 
    myDrawable = Drawable.createFromXml(res, res.getXml(R.xml.my_drawable)); 
} catch (Exception ex) { 
    Log.e("Error", "Exception loading drawable"); 
}