在 Android 中每秒更新 TextView [英] Update TextView every second in Android

查看:88
本文介绍了在 Android 中每秒更新 TextView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想每秒更新我的文本视图.单击按钮时,我正在调用一种方法,

i want to update my textview every second. on button click i am calling one method,

loopMethod(milli); //suppose milli= 50000 i.e 50 sec.

所以我的loopMethod(int m)如下:

public void loopMethod(int m){
    timer=(TextView) findViewById(R.id.timerText);
    if(m>=1000){
        try {
            timer.setText(""+m);//timer is a textview
            System.out.println(m);
            m=m-1000;
            Thread.sleep(1000);
        } catch(InterruptedException ex) {
            ex.printStackTrace();
        }
        loopMethod(m);
    }
}

所以我期望的是,我的计时器 textview 应该每秒打印一次 m 的值.但我只得到控制台输出,即 system.out.println(m)...控制台上的打印值工作正常......但它根本没有更新我的文本视图

so what i am expecting is, my timer textview should print the value of m every second. but i am getting only console output i.e system.out.println(m)... printing value on console working fine... but its not updating my textview at all

推荐答案

您可以使用以下代码:

Runnable updater;
void updateTime(final String timeString) {
    timer=(TextView) findViewById(R.id.timerText);
    final Handler timerHandler = new Handler();

    updater = new Runnable() {
        @Override
        public void run() {
            timer.setText(timeString);
            timerHandler.postDelayed(updater,1000);
        }
    };
    timerHandler.post(updater);
}

在这一行:

 timerHandler.post(updater);

时间将首次设置.即,更新程序将执行.第一次执行后,它将在每 1 秒的时间间隔后发布.它会每隔一秒更新您的 TextView.

time will set for the first time. i.e, updater will execute. After first execution it will be posted after every 1 second time interval. It will update your TextView every one second.

活动销毁时需要将其删除,否则会泄漏内存.

You need to remove it when the activity destroys, else it will leak memory.

@Override
protected void onDestroy() {
   super.onDestroy();
   timerHandler.removeCallbacks(updater);
}

希望能帮到你.

这篇关于在 Android 中每秒更新 TextView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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