2010-01-25 54 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"); 
}