java - 每次运行后计时器都会加速

标签 java android timer

我正在为 Android 制作一个简单的图像查看器。我还需要实现幻灯片放映。我有点完成了,除了我有一个烦人的错误。当我运行幻灯片(按一下按钮)时,它就可以工作了。但是,当我取消幻灯片并再次运行(相同的按钮)时,幻灯片会加速。

编辑:添加了固定代码,查看代码幻灯片部分的注释以了解需要修复的内容

   package csc2002.imageviewer;
   //imports

public class MainActivity extends Activity implements OnClickListener {
    static Timer timer = new Timer();
    int arrayIndex = 0;
    int checker=0;
    int start,delay = 1800;
    boolean toggle;


    private static Integer[] imageIds = { //Hard coded array
        R.raw.bulbasaur,R.raw.switch_brain,R.raw.quote,R.raw.victory,R.raw.penguins,R.raw.jellyfish,R.raw.koala};

    private static final int IMAGE_COUNT = imageIds.length;

    @Override
    public void onCreate(Bundle savedInstanceState) { // Called when the app is opened

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button back = (Button)findViewById(R.id.backButton);
        back.setOnClickListener(this);       
        Button next = (Button)findViewById(R.id.nextButton);
        next.setOnClickListener(this);
        Button slideshow = (Button)findViewById(R.id.slideButton);
        slideshow.setOnClickListener(this);
        displayImage();
    }

    // responsible for displaying the image and the name of the image.
    private void displayImage() { // Displays the image on the screen according the the current array index

        ImageView imgView = (ImageView) findViewById(R.id.myimage);             
        imgView.setImageResource(imageIds[arrayIndex]);
        TextView text = (TextView)findViewById(R.id.name);
        text.setText(imageIds[arrayIndex]);
    }

    // This method allows the cycling of images

    public void onClick(View v) {
        if(v.getId()==(R.id.backButton)){ //Back button
            arrayIndex--;

            if(arrayIndex==-1){
                arrayIndex = IMAGE_COUNT-1;
            }
            displayImage();
        }

        else if (v.getId()==(R.id.nextButton)){ //NextButton
            arrayIndex++;
        }
        if(arrayIndex==IMAGE_COUNT){
            arrayIndex = 0;
        }
        displayImage();

        if (v.getId()==R.id.slideButton){ //Slideshow button
            Button slideshow = (Button)findViewById(R.id.slideButton);
            toggle^= true;
            if(toggle==true){
                slideshow.setText("Stop Slideshow");
            }
            else{slideshow.setText("Start Slideshow");}
        }
        // Slideshow functionality

        if(toggle==true){
            //timer=new Timer(); //this was added in the correct solution(This was the main problem).
            timer.scheduleAtFixedRate(new TimerTask() {

                @Override
                public void run() {
                    if(toggle==true){
                        MainActivity.this.runOnUiThread(new Runnable() {
                            public void run() {
                                arrayIndex++;
                                if(arrayIndex==IMAGE_COUNT){
                                    arrayIndex=0;
                                }

                                displayImage();
                            }
                        });
                    }  
                }

            },start,delay);

        }
        else if(toggle==false){
            //timer.cancel(); This was added to correct the solution
        }
    }

    @Override 
    protected void onSaveInstanceState(Bundle outState) { //This saves data when the app is rotated
        outState.putInt("KEY", arrayIndex);
        super.onSaveInstanceState(outState);

    }
    @Override
    protected void onRestoreInstanceState(Bundle save){ //Restores Data after interruption
        super.onRestoreInstanceState(save);
        arrayIndex = save.getInt("KEY");
        displayImage();
    }


}

最佳答案

我在几年前做的一个项目中遇到过类似的问题。当然,我使用的是 Timer 对象,但我做了一些事情来解决这个问题:

  • 确保您明确停止计时器。
  • 重新初始化计时器,覆盖原来的计时器。

如果这些建议不起作用,请尝试发布更多代码。

编辑

public void onClick(View v) {
    //...
    if (v.getId()==R.id.slideButton){ //Slideshow button
        toggle^= true;
        if(toggle==true){
            timer = new Timer();
            timer.schedule(/*Whatever TimerTask you had here before*/);         
        }
        else{
            timer.cancel();
        }
    }//end if(slide button)
}//end onClick()

通过这种方式,计时器仅在单击切换按钮时启动或结束。单击按钮时创建计时器,再次单击时取消。绝不能同时有两个 Activity 计时器。我不太确定这将如何适应您现在的代码,但它应该适用于您第一次使用的代码。

关于java - 每次运行后计时器都会加速,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18084684/

相关文章:

java - 使用 eclipse 和我的 "module-info.java"生成 javadoc 时出错

java - 使用外键列的单向 OneToMany

Android 为什么这不会抛出错误的线程异常?

带 print 的 R Sys.sleep 在 while 循环中不起作用

Android Timer Task不等待预定的延迟时间

swift - 计时器不会在 WatchKit 上每秒触发一次

java - GWT 图像加载处理程序

java - 从一组集合中添加所有项目的最佳方法

java - Android 到 Java TCP/IP 读取速度太慢

java - Android - 具有嵌套信息和数组的 GenericJson