How to download AnimationDrawable from xml file

I have some custom BitmapStorage class that is not tied to either view or to another utility. And I have a born_animation.xml file that contains <animation-list> with animation frames:

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

I want to load the animation from an xml file as an AnimationDrawable using the Resource class (so that it will do all the parsing for me), extract the bitmaps and put them in my own storage class.

I have a problem:

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

WTF? Can someone explain this to me? The code compiles fine. All resources are available.

I tried another way - use ImageView for parsing (as described in dev manual)

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

The results are the same. it returns a null value.

Any hinsts would be greatly appreciated, thanks in advance.

+13
source share
3 answers

Yes, I found a reason! :)

This was my bad: I did not have the proper format for my animation.xml file:

  • I did not use android: namespace in the attributes (for some reason, I decided it was not required)
  • I removed the duration attribute in the <item> tags

After I fixed these things, res.getDrawable () began to return the correct instance of AnimationDrawable.

I had to look more closely at Resources.NotFoundException and getCause () to find out what was wrong :)

+6
source

Drawable

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

code:

 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); } 

View

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

This can be used to load resources from the xml directory.

 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"); } 
+3
source

All Articles