如何停止图像动画?

时间:2015-03-31 13:09:28

标签: android animation gallery

以下程序显示使用loadAnimation()方法自动设置动画的全屏图像。这是代码。

public class MainActivity extends ActionBarActivity {

/** Called when the activity is first created. */
public int currentimageindex=0;
Timer timer;
TimerTask task;
ImageView slidingimage;

private int[] IMAGE_IDS = {
        R.drawable.picture1, R.drawable.picture2, R.drawable.picture3,
        R.drawable.picture4
};
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final Handler mHandler = new Handler();


    // Create runnable for posting
    final Runnable mUpdateResults = new Runnable() {
        public void run() {

            AnimateandSlideShow();

        }
    };

    int delay = 1000; // delay for 1 sec.

    int period = 3000; // repeat every 4 sec.

    Timer timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {

        public void run() {

            mHandler.post(mUpdateResults);

        }

    }, delay, period);



}



/**
 * Helper method to start the animation on the splash screen
 */
private void AnimateandSlideShow() {


    slidingimage = (ImageView)findViewById(R.id.ImageView3_Left);
    slidingimage.setImageResource(IMAGE_IDS[currentimageindex%IMAGE_IDS.length]);

    currentimageindex++;

    Animation leftToRight = AnimationUtils.loadAnimation(this, R.anim.left_to_right);


    slidingimage.startAnimation(leftToRight);




}


}

正如您所见,全尺寸图片每4秒更换一次。现在我想要做的是在最后一张图像出现后停止动画(在这种情况下是图片4)。修复此问题后,我将尝试使用JSON从服务器获取图像。

谢谢你, 西奥。

1 个答案:

答案 0 :(得分:1)

1)你必须加载动画,直到你只有IMAGE_IDS数组中的图像

2)然后停止你的计时器

currentimageindex ++

下面的 AnimateandSlideShow()中添加以下内容
if(currentimageindex <= IMAGE_IDS.length)
        {
            Animation leftToRight = AnimationUtils.loadAnimation(this, R.anim.letf_anim);
            slidingimage.startAnimation(leftToRight);
        }
        else
        {
            timer.cancel();
        }

同时替换以下行

Timer timer = new Timer();

timer = new Timer();