AnimationDrawable 在 getBackground() 上获取 null

Sim*_*mon 2 null android animationdrawable

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

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
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是 animationImage.getBackground() 返回 null。

会欣赏你的提示:-)

谢谢,西蒙

小智 5

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

//animation = (AnimationDrawable) animatedImage.getBackground();
animation = (AnimationDrawable) animatedImage.getDrawable();
Run Code Online (Sandbox Code Playgroud)