【问题标题】:Pause thread inside for cycle (android)暂停线程内部循环(android)
【发布时间】:2014-05-02 19:16:47
【问题描述】:

今天我开始写一个简单的安卓应用程序。这个想法是当按下按钮时调用方法“click(View v)”,它将在 1 秒后将 TextField 的背景更改为随机颜色,例如 30 次

(长话短说:30 种不同的背景颜色以 1 秒的间隔变化)。

这是我所拥有的:

public void click(View v) {

    for(int i = 0; i >= 30; i++){       
       Random rand = new Random();
       final int red = rand.nextInt(255);
       final int green = rand.nextInt(255);
       final int blue = rand.nextInt(255);
       final TextView tf = (TextView) findViewById(R.id.textView1);

       // SLEEP 1 SECOND HERE ...
       Handler handler = new Handler();
       handler.postDelayed(new Runnable() {
           public void run() {
            tf.setBackgroundColor(Color.rgb(red, green, blue));
           }
        }, 1000);   
    }
}

但是当我按下按钮时没有任何反应。作为初学者,我将非常感谢任何关于如何解决此问题的建议。

【问题讨论】:

    标签: android for-loop sleep android-handler


    【解决方案1】:

    尝试调用 tf.invalidate() 来强制它重绘。

    此外,如果您希望它每秒更新 30 秒,您应该将 1000 更改为 i * 1000(而不是注释所暗示的休眠)。正如目前所写,所有 postDelayed 大约在同一时间结束。

    您也可以将处理程序的创建移到循环之外,无需创建多个。

    【讨论】:

    • 感谢改进,但不幸的是 tf.invalidate() 对我不起作用。但是,当我删除 for 循环时,它可以正常工作(在 1 秒后按下按钮背景颜色更改一次。)
    【解决方案2】:

    3 小时后,我终于解决了这个问题。 for 循环标头中有错误。 正好在 i>=30。像这样写,循环中的代码永远不会启动。它必须是 i 。多么愚蠢的错误-_-

    所以现在的代码是这样的:

    public void click(View v) {
        Handler handler = new Handler();
        final Random rand = new Random();
        for(int i=1; i <= 30; i++){         
            handler.postDelayed(new Runnable() {
                public void run() {
                    int red = rand.nextInt(255);
                    int green = rand.nextInt(255);
                    int blue = rand.nextInt(255);
                    TextView tf = (TextView) findViewById(R.id.textView1);
                    tf.setBackgroundColor(Color.rgb(red, green, blue));                 
                }
            }, i * 1000);                   
        }       
    }
    

    它正在工作!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多