我有一些自定义的类位图表,没有任何视图或任何视图 - 实用程序。我有born_animation.xml文件,其中包含u003Canimation-list>使用动画框架:

<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 

wtf?有人可以向我解释吗?代码填充正常。所有资源都到位。

我尝试了另一种方法 - 使用ImageView进行解析(如开发指南中所述)

ImageView view = new ImageView(context); 
view.setBackgroundResource(R.drawable.born_animation); 
AnimationDrawable drawable = (AnimationDrawable)view.getBackground(); 
assertTrue( drawable != null ); <= fails! it's null 

结果是相同的。它返回可绘制的无效。

感谢提前。

有帮助吗?

解决方案 2

是的,我找到了原因! :)

这是我的不好:我没有anistion.xml文件的正确格式:

  • 我没有在属性中使用Android:名称空间(由于某种原因,我认为不需要)
  • 我删除了“持续时间”属性u003Citem>标签

修复这些内容后,res.getDrawable()开始返回正确的AnimationDrawable实例。

必须更精确地查看资源。NotFoundException,并且是GetCause()来找出出了什么问题:)

其他提示

可绘制

<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" />

这可用于从“ 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"); 
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top