【问题标题】:How Do I Pause and Resume a For Loop?如何暂停和恢复 For 循环?
【发布时间】:2013-02-05 13:41:45
【问题描述】:

我是 Android 的菜鸟,我正在尝试从字符串数组列表中循环文本并将它们显示在文本切换器中。我希望文本每两秒更改一次。我使用this SO 问题作为我的指南,使用按钮切换文本没有问题。但是,当我尝试使用具有 2 秒延迟的 for 循环循环文本时,它仅显示 arrayList 中的第一个文本。如何让循环在暂停的情况下连续执行?非常感谢任何帮助。

我的代码;

private void updateCounter()
{   

    try{
    for (int i=0; i< CoinShowReader.tickercontent.size(); i++){                             

        mHandler.postDelayed(new Runnable() { 
             public void run() { 
                m_switcher.setText((CoinShowReader.tickercontent.get(CoinShowReader.m_counter)));               
                CoinShowReader.m_counter++;
             } 
        }, 2000);

        }

    }catch(Exception e){
        e.printStackTrace();    
    }
}  

【问题讨论】:

    标签: android multithreading loops wait postdelayed


    【解决方案1】:

    删除循环,你不需要它,只需像这样在处理程序中安排 anther runnable:

    void updateTextView(){
            m_switcher.setText((CoinShowReader.tickercontent.get(CoinShowReader.m_counter)));               
            CoinShowReader.m_counter++;
    
                mHandler.postDelayed(new Runnable() { 
                                 public void run() { 
                                   updateTextView(); 
            } } ,2000);  }
        }
    

    这样每次调用updateTextView() 都会安排下一次调用,依此类推...

    注意: 不要忘记插入触发器来停止该行为,因为它是无穷大的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-15
      • 1970-01-01
      相关资源
      最近更新 更多