【问题标题】:AnimationDrawable getting null on getBackground()AnimationDrawable 在 getBackground() 上为空
【发布时间】:2012-10-28 14:39:05
【问题描述】:

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

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。

将感谢您的提示 :-)

谢谢, 西蒙

【问题讨论】:

  • 嗨,我知道这是旧的,但你找到任何解决方案了吗?谢谢

标签: android null animationdrawable


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    希望这会对你有所帮助;)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-16
      • 1970-01-01
      • 2015-05-29
      • 1970-01-01
      相关资源
      最近更新 更多