如何动态地更改按钮文本为每3秒的机器人? [英] how to change button text dynamically for every 3 sec in android?

查看:87
本文介绍了如何动态地更改按钮文本为每3秒的机器人?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序,我想更改按钮文本为每3秒。

in my application i want to change button text for every 3 sec.

推荐答案

设置的定时器的运行 TimerTask的每3秒。该 TimerTask的只需调用按钮的的的setText 方法来改变按钮的文字。你将不得不在UI线程内做到这一点,所以你应该使用发表运行的 Runnable的对象,将进行更新的正确的线程。

Set up a Timer to run a TimerTask every 3 seconds. The TimerTask only has to call the button's setText method to change the button's text. You would have to do this within the UI thread, so you should use post to run a Runnable object that will perform the update an the correct thread.

例如,在下面的活动中,字母A被添加到该按钮的文本每三秒钟:

For example, in the following activity, the letter "A" is added to the button's text every three seconds:

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");
                }
            });
        }
    }
}

这篇关于如何动态地更改按钮文本为每3秒的机器人?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆