设置
Timer以每3秒运行一次
TimerTask.
TimerTask只需要调用按钮的
setText方法来更改按钮的文本.您必须在UI线程中执行此操作,因此您应该使用post来运行将执行更新的正确线程的
Runnable对象.
例如,在以下活动中,字母“A”每三秒添加到按钮的文本中:
public class ButtonTest extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button subject = new Button(this);
subject.setLayoutParams((new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT)));
subject.setText("A");
setContentView(subject);
Timer timing = new Timer();
timing.schedule(new Updater(subject), 3000, 3000);
}
private static class Updater extends TimerTask {
private final Button subject;
public Updater(Button subject) {
this.subject = subject;
}
@Override
public void run() {
subject.post(new Runnable() {
public void run() {
subject.setText(subject.getText() + "A");
}
});
}
}
}