ITeye博客

解决Android帧动画在Oncreate中启动只显示第一帧

berdy · 2013-06-26 17:18 · Android · 移动开发 · Markdown

做了个简单的帧动画,在onCreate方法中start,发现只能看到第一帧


<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false" >

    <item
        android:drawable="@drawable/fire01"
        android:duration="200"/>
    <item
        android:drawable="@drawable/fire02"
        android:duration="200"/>
    <item
        android:drawable="@drawable/fire03"
        android:duration="200"/>
    <item
        android:drawable="@drawable/fire04"
        android:duration="200"/>
    <item
        android:drawable="@drawable/fire05"
        android:duration="200"/>
    <item
        android:drawable="@drawable/fire06"
        android:duration="200"/>
    <item
        android:drawable="@drawable/fire07"
        android:duration="200"/>
    <item
        android:drawable="@drawable/fire08"
        android:duration="200"/>
    <item
        android:drawable="@drawable/fire09"
        android:duration="200"/>

</animation-list>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
	>
	<ImageView
        android:id="@+id/fire_img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@drawable/fire_anim" />
</RelativeLayout>


	ImageView fireImg = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		ImageView fireImg = (ImageView) findViewById(R.id.fire_img);
		final AnimationDrawable animDrawable = (AnimationDrawable) fireImg
				.getBackground();
		animDrawable.start();
	}

stackoverflow 上发现一个解决办法


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		ImageView fireImg = (ImageView) findViewById(R.id.fire_img);
		final AnimationDrawable animDrawable = (AnimationDrawable) fireImg
				.getBackground();
		fireImg.post(new Runnable() {
			@Override
			public void run() {
				animDrawable.start();
			}
		});
	}

或者在Activity中的onWindowFocusChanged方法中start


	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		if (fireImg != null) {
			AnimationDrawable animDrawable = (AnimationDrawable) fireImg
					.getBackground();
			animDrawable.start();
		}
	}

评论(1)

  1. #1 楼 · plmmmmlq · 2014-12-20 22:25

    爱死你了,困惑我几天的问题终于解决了。自定义dialog中加载帧动画,在2.3系统中不动,4.0的系统就正常,求原因。第二种方法试过,无效,我用第一种。感谢分享。

评论功能维护中,当前仅展示历史评论。