Переключение изображений с задержкой

1

В настоящее время я делаю свое первое приложение для Android, и мне нужна помощь. Приложение, которое я делаю, это игра Simon.

Итак, у меня есть 2 вопроса:

1) Когда пользователь нажимает одну из цветных кнопок, фоновое изображение кнопки переключается на светящуюся версию. Но как я могу заставить кнопку снова иметь исходное фоновое изображение после небольшой задержки? Я попробовал его с заданием таймера (только для красной кнопки), но приложение падает, когда я пытаюсь это сделать.

2) Это также должно происходить автоматически, когда компьютер проходит через комбинацию цветов. Есть ли способ включить его в отдельную функцию, которая может быть вызвана?

Здесь код: пакет android.Simon;

import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; импортировать android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Хронометр; import android.widget.TextView; import java.util.Random; import java.util.Timer; import java.util.TimerTask;

открытый класс Simon extends Activity {   Хронометр mЧетрометр;   int [] ComArray = new int [100];   int gebruikergetal;   int я = 0;   int j = 0;   int aantalcomgetallen = 1;//для определения количества цветов, которые компьютер должен показывать   int gebruikerteller;//переменная, чтобы определить, поворачивается ли пользователь   int startstop = 1;   int delay = 1000;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button button;
    final TextView textView = (TextView) findViewById(R.id.textView1);
    final Button button1;
    final Button button2;
    final Button button3;
    final Button button4;

    for(i=0;i<100;i++){
        for(j=0;j<4;j++){
            ComArray[i] = RandomCreator.getRandomInt(1, 4);
        }
    }

    i=0;

    mChronometer = (Chronometer) findViewById(R.id.chronometer1);

    button = (Button) findViewById(R.id.button5);       
    button1 = (Button) findViewById(R.id.button1);
    button2 = (Button) findViewById(R.id.button2);
    button3 = (Button) findViewById(R.id.button3);
    button4 = (Button) findViewById(R.id.button4);

    final View.OnClickListener Blauw = new OnClickListener() {
        public void onClick(View v){
            //int GebruikerArray[] = new int[i];
            gebruikergetal = 2;
            button1.setBackgroundDrawable(getResources().getDrawable(0x7f020001));
                    //here i'm switching the background image of the button
            textView.setText(String.valueOf(gebruikergetal));
            if(gebruikergetal!=ComArray[i]){
                textView.setText("Game Over");
            }
            i++;
        }
    };

    final View.OnClickListener Groen = new OnClickListener() {
        public void onClick(View v){
            //int GebruikerArray[] = new int[i];
            gebruikergetal = 3;
            button2.setBackgroundDrawable(getResources().getDrawable(0x7f020003));
            textView.setText(String.valueOf(gebruikergetal));
            if(gebruikergetal!=ComArray[i]){
                textView.setText("Game Over");
            }
            i++;
        }
    };

    final View.OnClickListener Rood = new OnClickListener() {
        public void onClick(View v){
            //int GebruikerArray[] = new int[i];
            Timer timer = new Timer();

            gebruikergetal = 1;
            button3.setBackgroundDrawable(getResources().getDrawable(0x7f020006));
            //this is where I try out the timer task, but the app crashes
                    TimerTask task = new TimerTask(){
                public void run(){
                        button3.setBackgroundDrawable(getResources().getDrawable(0x7f020005));
                }
            };
            timer.scheduleAtFixedRate(task, 0, 1000);
            textView.setText(String.valueOf(gebruikergetal));
            if(gebruikergetal!=ComArray[i]){
                textView.setText("Game Over");
            }
            i++;
        }
    };

    final View.OnClickListener Geel = new OnClickListener() {
        public void onClick(View v){
            //int GebruikerArray[] = new int[i];
            gebruikergetal = 4;
            button4.setBackgroundDrawable(getResources().getDrawable(0x7f020009));
            textView.setText(String.valueOf(gebruikergetal));
            if(gebruikergetal!=ComArray[i]){
                textView.setText("Game Over");
            }
            i++;
        }
    };
    View.OnClickListener mStartListener = new OnClickListener() {
        public void onClick(View v) {
            if(startstop == 1){
                mChronometer.start();
                textView.setText("Com Turn!");
                button1.setOnClickListener(Blauw);
                button2.setOnClickListener(Groen);
                button3.setOnClickListener(Rood);
                button4.setOnClickListener(Geel);
                startstop = 0;
            }
            else{
                startstop = 1;
                mChronometer.stop();
                textView.setText("");
            }
        }
    };
    button.setOnClickListener(mStartListener);
}

}

Если кто-то может помочь, я бы очень признателен. спасибо

Теги:
applet

1 ответ

1

Бросьте все, что вам нужно сделать в методе, и используйте то, что называется обработчиком и запускается.

private Handler mHandler;

mHandler = new Handler(); 
mHandler.postDelayed(switchImages, delay (in milliseconds); 

 private Runnable switchImages = new Runnable() {
        public void run() {
            //Whatever method you make call here
                mHandler.postDelayed(switchImages, delay); 
                //This will call it again therefore continuous updating;
        }
    };

Ещё вопросы

Сообщество Overcoder
Наверх
Меню