2

我正在尝试使用以下代码为示例程序设置动画:

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。

将不胜感激你的提示:-)

谢谢,西蒙

4

2 回答 2

5

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

//animation = (AnimationDrawable) animatedImage.getBackground();
animation = (AnimationDrawable) animatedImage.getDrawable();
于 2014-12-04T07:38:59.707 回答
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();
            }
        }
    });
}
于 2013-05-31T08:12:59.453 回答