2016-01-18 31 views
4

我正在写一个小程序来每5秒更新一次TextView。但我无法更新每隔5秒我的TextView的文本,尤其是当它涉及到持续ArrayList的项目,如:C以下代码使用Timer和ArrayList更新TextView

我下面this教程

public class MainActivity extends Activity { 

Timer timer; 
MyTimerTask myTimerTask; 
List<String> list; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    textCounter = (TextView)findViewById(R.id.counter); 

    timer = new Timer(); 
    myTimerTask = new MyTimerTask(); 

    timer.schedule(myTimerTask, 1000, 5000); 

    .... 

    list = new ArrayList<String>(); 
    list.add("A"); 
    list.add("B"); 
    list.add("C"); 

} 

class MyTimerTask extends TimerTask { 

    @Override 
    public void run() { 

    runOnUiThread(new Runnable(){ 

    @Override 
    public void run() { 
    for(int i=0; i<list.size(); i++) { 
     textCounter.setText(list.get(i).toString()); 
    } 
    }}); 
    }} 
+0

相反的迭代列表,你为什么不设置TextView的有一次在一个文本。 –

+0

不要使用计时器任务它不能正常工作,请使用处理程序。 –

+0

你在哪里调用timer.start()方法来启动Timer。 –

回答

2

不要重复列表每次运行方法都要调用。而是从列表中获取一个项目并将其设置为TextView。下面给出

private int count =0; 
private class MyTimerTask extends TimerTask { 
    @Override 
    public void run() { 
     runOnUiThread(new Runnable(){ 
      @Override 
      public void run() { 
       textCounter.setText(list.get(count%list.size).toString()); 
       count++; 
      }); 
     } 
    } 
} 
+0

您能以简单的方式显示我吗? – Sun

+0

@孙我刚刚修改了代码中的几行。你了解上面的代码吗? –

+0

@孙你只需要修改'MyTimerTask'类不是所有的代码。 –

1

更改 MyTimerTask类。

private int position = 0; 

class MyTimerTask extends TimerTask { 

    @Override 
    public void run() { 

     runOnUiThread(new Runnable() { 

      @Override 
      public void run() { 
       if (position >= list.size()) { 
        position = 0; 
       } 

       textCounter.setText(list.get(position).toString()); 
       position++; 

      } 
     }); 
    } 


} 
+0

不幸的是,当涉及到最后一项... – Sun

+0

我编辑了我的答案,请现在检查。 @Sun –

+0

现在它只显示第一个ArrayList .... – Sun

1

而不是使用TimerTask的你应该使用Handler用于更新TextView

Handler mHandler = new Handler(); 
final Runnable runnable = new Runnable() { 
    int count = 0; 
    @Override 
    public void run() { 
     count++; 
     textCounter.setText(list.get(count).toString()); 
     mHandler.postDelayed(this, 5000); // five second in ms 
    } 
}; 
mHandler.postDelayed(runnable, 1000); 

我希望这可以帮助你。

1

这里我有一些代码片段,它只是每5秒钟更新Textview。

第1步: 首先你只是做一个saperate方法,其中的TextView是更新类似以下。

private void updateTextView(){ 
    /** 
    * Write Your Textview Update Code 
    */ 

} 

步骤2 可运行类的申报对象,其只需调用updateTextview方法中的一些特定的时间之后。

Runnable run = new Runnable() { 

    @Override 
    public void run() { 

     updateTextView(); 

    } 
}; 

步骤3 可以启动此可运行使用下面的代码。

YOUR_TEXTVIEW.postDelayed(run,5000); 

我希望你清楚我的想法。

祝您好运