如何在android中每3秒动态更改按钮文本?

dee*_*thi -2 android

在我的应用程序中,我想每3秒更改一次按钮文本.

Kla*_*rth 5

设置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");
                }
            });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)