Я делаю простой просмотрщик изображений для Android. Мне также нужно реализовать слайд-шоу. Я вроде как сделал, за исключением того, что у меня есть раздражающая ошибка. Когда я запускаю слайд-шоу (нажатием кнопки), он работает. Но когда я отменяю слайд-шоу и запускаю его снова (та же кнопка), слайд-шоу ускоряется.Таймер ускоряется после каждого запуска
EDIT: Добавлен фиксированный код, обратите внимание на комментарии в слайд-шоу части кода, чтобы увидеть, что нужно фиксируя
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();
}
}
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Timer.html#schedule%28java.util.TimerTask,%20long,%20long%29 TimerTask класс не предлагает гарантии в реальном времени: он планирует задачи с использованием метода Object.wait (long). – dseibert
Вы добавляете событие таймера к своему планировщику при каждом нажатии кнопки? Если это так, у вас одновременно есть несколько событий таймера, которые будут выглядеть как скорость до вас. – Tansir1
+1 для того, чтобы не пометить это как Android. – supersam654