2015-03-31 56 views
0

以下程序显示使用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的服务器获取图像。

谢谢 Theo。

回答

1

1)您有直到只有你有图像IMAGE_IDS阵列

2)然后停止你的定时器AnimateandSlideShow()下面currentimageindex ++

添加以下行来加载动画

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(); 
+0

是。那做了这个工作。非常感谢。我把你的答案标记为一个:) – Theo 2015-03-31 14:05:20