我正在尝试使用不同的字符串每3秒更新一次TextView。我有一个处理程序和runnable设置,但是当我运行它时,它会自动显示最后一个setText。我已经尝试将ms更改为3000,6000等,并且在运行之前也尝试过removeCallbacks。任何帮助将不胜感激!
final Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.workout);
final Runnable r = new Runnable(){
@Override
public void run(){
TextView text = (TextView)findViewById(R.id.textView4);
text.setText("1");
handler.postDelayed(this, 3000);
text.setText("2");
handler.postDelayed(this, 3000);
text.setText("3");
handler.postDelayed(this, 3000);
text.setText("4");
handler.postDelayed(this, 3000);
text.setText("5");
}
};
handler.postDelayed(r, 0);
}
答案 0 :(得分:0)
像这样更改你的代码
private String[] messages = {"1", "2", "3", "4", "5"};
final Handler handler = new Handler();
private int nextIndex;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.workout);
final TextView text = (TextView)findViewById(R.id.textView4);
final Runnable r = new Runnable(){
@Override
public void run(){
if (messages.length > nextIndex) {
text.setText(messages[nextIndex++]);
handler.postDelayed(this, 3000);
}
}
};
handler.postDelayed(r, 0);
}