简体   繁体   English

Java for循环中的Android处理程序计时器

[英]java android handler timer in for loop

I have 4 ImageButton and I want to change the images of them randomly FOR 2 seconds. 我有4个ImageButton,我想随机更改它们的图像2秒钟。 But it doesn't work. 但这是行不通的。 What is the problem here? 这里有什么问题? I don't really understand the work of Handlers. 我不太了解Handlers的工作。 I want: change the image of buttonimage, wait 5 seconds, change back the image of buttonimage 我想要:更改buttonimage的图像,等待5秒钟,再更改一下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. 也许问题出在您的图像上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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