在AsyncTask中运行图像/动画序列



我创建了一个自定义的ProgressDialog,它有一个生动的ImageView。但这给错误使用在AsyncTask执行。AsyncTask没有工作。我试图使用动画与runonuthread和不工作。我如何在运行AsyncTask时使用这个动画?

layout_progress.xml (only image)

<ImageView
    android:id="@+id/ivLoading"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@anim/loading"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="100dp"/>

loading.xml(动画)

<?xml version="1.0" encoding="utf-8"?>
<animation-list android:id="@+id/animation" android:oneshot="false"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/load5_1" android:duration="150" />
    <item android:drawable="@drawable/load5_2" android:duration="150" />
    <item android:drawable="@drawable/load5_3" android:duration="150" />
    <item android:drawable="@drawable/load5_4" android:duration="150" />
    <item android:drawable="@drawable/load5_5" android:duration="150" />
    <item android:drawable="@drawable/load5_6" android:duration="150" />
    <item android:drawable="@drawable/load5_7" android:duration="150" />
    <item android:drawable="@drawable/load5_8" android:duration="150" />
    <item android:drawable="@drawable/load5_9" android:duration="150" />
    <item android:drawable="@drawable/load5_10" android:duration="150" />
</animation-list>

方法显示自定义进度对话框

    public void show() {
        super.show();
        setContentView(layoutId);
        final ImageView imageView = (ImageView) findViewById(R.id.ivLoading);
        final AnimationDrawable anim = (AnimationDrawable) imageView.getDrawable();
        final Runnable run = new Runnable() {

@Override
        public void run() {
            anim.start();
        }
    };
    imageView.post(run);
    //test 2 - doesnt work
    /*
    final Runnable run = new Runnable() {
        @Override
        public void run() {
            anim.start();
            imageView.post(this);
        }
    };
    activity.runOnUiThread(run);
    */
}

你不应该在AsyncTask中这样做。UI的操作应该只在UI线程中完成。

这里有一个简单的例子来说明你想要达到的目的:http://developer.android.com/guide/topics/graphics/drawable-animation.html

在确定ImageView已附加到视图层次结构后,尝试启动动画。引用我发布的链接:

需要注意的是,在AnimationDrawable上调用的start()方法不能在Activity的onCreate()方法中调用,因为AnimationDrawable还没有完全附加到窗口上。如果你想要立即播放动画,而不需要交互,那么你可能想要从Activity中的onWindowFocusChanged()方法调用它,当Android将你的窗口变为焦点时,该方法将被调用。

最新更新