javaandroidandroid-drawableandroid-handlerpostdelayed

Simon Says button color won't return to normal after button press


public void flashButton(int color) {
    final ImageView colors = findViewById(R.id.buttonsImage);
    final int newColor = color;

    Handler handler = new Handler();
    final Runnable r = new Runnable() {
        public void run() {
            if(newColor == 1)
                colors.setImageResource(R.drawable.green_activated_png);
            if(newColor == 2)
                colors.setImageResource(R.drawable.yellow_activated_png);
            if(newColor == 3)
                colors.setImageResource(R.drawable.red_activated_png);
            if(newColor == 4)
                colors.setImageResource(R.drawable.blue_activated_png);

            System.out.println("Flashed color: " + newColor);
        }
    };
    handler.postDelayed(r, 1000);

    colors.setImageResource(R.drawable.normal_buttons);
    System.out.println("Returned Color.");
}

The button color is being changed for each button with R.drawable.green_activated_png). Then, I'm changing it back with (R.drawable.normal_buttons). I'm thinking my problem is in handler.postDelayed(r, 1000). But the color ins't changing back to normal after the user presses the correct color.


Solution

  • You are kind of doing it in just opposite.You have to change the color of Button immediately after pressing it and you will have to keep your returned color into postDelayed so that after the delay of given time it turns into normal color.

    public void flashButton(int color) {
        final ImageView colors = findViewById(R.id.buttonsImage);
        final int newColor = color;
        if(newColor == 1)
            colors.setImageResource(R.drawable.green_activated_png);
        if(newColor == 2)
            colors.setImageResource(R.drawable.yellow_activated_png);
        if(newColor == 3)
            colors.setImageResource(R.drawable.red_activated_png);
        if(newColor == 4)
            colors.setImageResource(R.drawable.blue_activated_png);
        System.out.println("Flashed color: " + newColor);
    
        Handler handler = new Handler();
        final Runnable r = new Runnable() {
            public void run() {
                colors.setImageResource(R.drawable.normal_buttons);
                System.out.println("Returned Color.");
            }
        };
        handler.postDelayed(r, 1000);
    }