简体   繁体   中英

java android handler timer in for loop

I have 4 ImageButton and I want to change the images of them randomly FOR 2 seconds. But it doesn't work. What is the problem here? I don't really understand the work of Handlers. I want: change the image of buttonimage, wait 5 seconds, change back the image of buttonimage

for (int i = 0; i < cpu_array.length; i++) {
        actual = cpu_rnd.nextInt(4);
        cpu_array[i] = actual;
        switch (actual) {
        case 0:
            BlueButton.setImageResource(R.drawable.blue_a);
            break;
        case 1:
            RedButton.setImageResource(R.drawable.red_a);
            break;
        case 2:
            GreenButton.setImageResource(R.drawable.green_a);
            break;
        case 3:
            PurpleButton.setImageResource(R.drawable.purple_a);
            break;

        default:
            break;
        }


        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // Do something after 2s = 2000ms
                BlueButton.setImageResource(R.drawable.blue);
                RedButton.setImageResource(R.drawable.red);
                GreenButton.setImageResource(R.drawable.green);
                PurpleButton.setImageResource(R.drawable.purple);
            }
        }, 2000);

    }

This code worked for me:

   final Button startBookmarksButton = (Button) findViewById(R.id.start_bookmarks_button);
   startBookmarksButton.setBackgroundColor(Color.BLUE);
   new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            startBookmarksButton.setBackgroundColor(Color.GREEN);
        }
    }, 2000);

So I think the problem might be somewhere else in your code. Are you sure the random number logic in your loop is working ? Why don't you try getting the delay working first and then debug the random part. Or perhaps the problem is with your images.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM