0

我创建了一个简单的演示项目,它使用 Android 的 AnimationDrawable 类来制作动画。这是我的java代码:

public class TestAnimationActivity extends Activity {
    /** Called when the activity is first created. */

    ImageView imgCircleWhite,imgCircleYellow;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        imgCircleYellow = (ImageView)findViewById(R.id.imgCircleYellow);

        animateState(true, imgCircleYellow);

    }

    public void animateState(boolean flag,ImageView imageView)
    {
        imgCircleYellow.setBackgroundResource(R.drawable.animate_circle_sensor_1);
        AnimationDrawable yourAnimation = (AnimationDrawable) imageView.getBackground(); 
        if(!flag)
        {   
            //imageView.getAnimation().reset();
            imageView.setBackgroundResource(R.drawable.circle_label_white_1);           
            yourAnimation.stop();           
        }
        else
        {
            imageView.setBackgroundResource(R.drawable.animate_circle_sensor_1); 
            yourAnimation = (AnimationDrawable) imageView.getBackground(); 
            yourAnimation.start();
        }
    }
}

这是我的 main.xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <ImageView android:id="@+id/imgCircleYellow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/circle_label_yellow_1"/>

</LinearLayout>

下面是我的 animate_sensor_circle_1.xml,我已将其放入可绘制文件夹中以供使用:

<?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/circle_label_white_2"
        android:duration="50"/>
    <item
        android:drawable="@drawable/circle_label_yellow_1"
        android:duration="50"/>
</animation-list>

当我运行该应用程序时,仅显示上述 xml 文件中的第一项,但动画不会像应有的那样重复出现。谁能指导我哪里出错了?

4

1 回答 1

0

现在不是打电话的合适时机AnimationDrawable.start()。您应该在视图初始化完成后执行此操作。试试这个:

final ImageView imgCircleYellow = (ImageView)findViewById(R.id.imgCircleYellow);
imgCircleYellow.setBackgroundResource(R.drawable.animate_circle_sensor_1);
imgCircleYellow.post(new Runnable() {
    @Override
    public void run() {
        animateState(true, imgCircleYellow);
    }

检查此以获取更多信息:https ://stackoverflow.com/a/5490922/813135

于 2012-10-31T08:06:50.720 回答