2012-10-28 56 views
1

我想用下面的代碼,以動畫的一個範例程序:AnimationDrawable上的getBackground()獲得空

AnimationDrawable animation; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.loading); 

    ImageView animatedImage = (ImageView) findViewById(R.id.animation); 
    animatedImage.setBackgroundResource(R.drawable.animate_bag); 
    animation = (AnimationDrawable) animatedImage.getBackground(); 
} 


public void startAnimate(View v) 
{ 
    if (animation != null) 
     animation.start();   
} //eof OnClick 

XML文件是:

<Button android:id="@+id/button" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Animate" 
     android:onClick="startAnimate" /> 
    <ImageView 
     android:id="@+id/animation" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:src="@drawable/animate_bag" /> 


</LinearLayout> 

我的問題是, animatedImage.getBackground()返回null。

會感謝您的提示:-)

感謝, 西蒙

+0

嗨,我知道這是舊的,但你有沒有找到解決辦法?謝謝 – Youssef

回答

0

希望這會幫助你;)

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.loading); 

    final ImageView animatedImage = (ImageView) findViewById(R.id.animation); 
    animatedImage.setBackgroundResource(R.drawable.animate_bag); 


    animatedImage.post(new Runnable() { 

     @Override 
     public void run() { 
      AnimationDrawable frameAnimation = (AnimationDrawable) animatedImage.getDrawable(); 
      if (frameAnimation != null) { 
       frameAnimation.start(); 
      } 
     } 
    }); 
} 
3

如果的getBackground()返回null,使用getDrawable()方法。

//animation = (AnimationDrawable) animatedImage.getBackground(); 
animation = (AnimationDrawable) animatedImage.getDrawable();