【问题标题】:How to use android handler in a loop如何在循环中使用android处理程序
【发布时间】:2016-11-14 19:54:59
【问题描述】:

我正在构建我的第一个 android 应用程序,并且我正在尝试制作一个记忆游戏。无论如何,我需要让一组按钮改变颜色1秒钟,然后按顺序返回到原来的颜色,例如:button1变为黄色,保持1秒钟然后返回灰色,然后button2变为黄色1 秒然后返回,依此类推。我尝试使用处理程序,但它始终仅在最后一次迭代后才有效,这是我的代码:

for (i = 0; i < 9; i++) {

                    buttonList.get(i).setBackgroundColor(Color.YELLOW);


                    runnable =new Runnable(){
                        @Override
                        public void run() {

                             buttonList.get(i).setBackgroundColor(Color.GRAY);

                        }
                    };
                    handler.postDelayed(runnable,1000);}

我做错了什么?

编辑 找到了怎么做。首先我需要创建一个可运行的类,它接受参数 ex MyRunnable 实现 Runnable(使用 Runnable 接口),然后编写一个使用这个参数的方法,我不能这样做常规的,因为它取决于 i 并且 i 随迭代而变化。

【问题讨论】:

  • 因为十次迭代完成的速度快于 1 秒

标签: android loops android-handler


【解决方案1】:

您需要在每个循环中创建一个新的 Runnable,因为所有 9 个延迟的帖子都在运行您在第 9 个和最后一个循环中创建的相同可运行对象,因为该循环无疑需要不到一秒的时间来完成。所以尝试这样的事情:

for (i = 0; i < 9; i++) {
    buttonList.get(i).setBackgroundColor(Color.YELLOW);
    Runnable runnable = new Runnable(){
         @Override
         public void run() {
             buttonList.get(i).setBackgroundColor(Color.GRAY);
         }};
    handler.postDelayed(runnable,1000);
 }

【讨论】:

  • 感谢您的回复,但还是一样。我认为我不能使用 i 并且需要使用某种方式将其值传递给 runnable 而不是本身,但我不知道如何
【解决方案2】:

您正在同步(同时)将所有按钮的颜色设置为黄色,并创建 9 个异步任务(每个按钮一个)以在一秒后将颜色更改为灰色。这意味着所有按钮将在大约 1 秒后(或多或少)同时将颜色变回灰色。

将处理程序视为您向其中添加任务的队列。调用postDelayed()是在安排你的任务在以后执行,但是都是同时安排的,所以以后都会同时执行。

我没有运行它,但我认为这种方法更符合您的要求:

// Those are fields
private int buttonIndex = 0;
private boolean yellow = false;
private final Handler handler = new Handler(new Handler.Callback() {
    @Override
    public void handleMessage(Message msg) {
        if (!yellow) {
            buttonList.get(buttonIndex).setBackgroundColor(Color.YELLOW);
            handler.sendEmptyMessageDelayed(0, 1000);
        } else {
            buttonList.get(buttonIndex).setBackgroundColor(Color.GRAY);
            if (++buttonIndex < 9) handler.sendEmptyMessage(0);
        }
        yellow = !yellow;
}});

// Call this to start the sequence.
handler.sendEmptyMessage(0);

请注意,我使用的是sendEmptyMessage*() 而不是post*(),但可以使用任何一种方法。此外,处理程序的消息(任务)可以有输入参数,所以最好使用它们。

【讨论】:

  • 感谢您的回复,不幸的是仍然如此。
猜你喜欢
  • 2013-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多