如何在 Android 中循环时刷新 TextView? [英] How to refresh a TextView while looping in Android?

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

问题描述

我有这个:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    TextView debugView = (TextView)findViewById(R.id.debugView);

    for(int i=0;i<100;i++) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        debugView.setText(Integer.toString(i));
    }

}

我希望它每次通过循环更新文本视图,所以我会得到:1, 2, 3, ... 99

I would expect it to update the text view each time through the loop so I would get: 1, 2, 3, ... 99

相反,应用程序在 10 秒内什么都不做,然后输出:99

Instead the app does nothing for 10 seconds and then outputs: 99

我猜我需要在循环期间刷新 TextView.我是 Android 开发的新手.有人可以告诉我这是否是完成此任务的最佳方法吗?

I am guessing that I need the TextView to refresh during the loop. I am new to Android development. Can somebody please tell me if this is the best way to accomplish this?

我的最终目标是能够处理音频样本以构建吉他调音器.我试图简单地验证应用程序是否响应外部音频,并且我想更新一个 TextView 来证明这一点.请告知是否有更好的方法来做到这一点.

My eventually goal is to be able to process audio samples to build a guitar tuner. I am trying to simply verify visually that the app is responding to external audio and I want to update a TextView to demonstrate that. Please advise if there is a better way to do this.

推荐答案

你的问题是你在 onCreate() 中运行你的循环.这发生在您的 Activity 显示之前的 UI 线程上.

Your problem is that you are running your loop in onCreate(). This is happening on the UI thread before your Activity is displayed.

看看 Android 中的 Activity 生命周期.它表明 onCreate 只是 Activity 创建的阶段之一.您要做的是在后台线程上运行循环并使用 runOnUiThread 发布通知以将 TextView 更新到 UI 线程.Christian 的回答显示了如何做到这一点.

Take a look at the Activity lifecycle in Android. It shows onCreate is just one of the stages in the Activity creation. What you'll want to do is run the loop on a background thread and post the notification to update the TextView onto the UI thread using runOnUiThread. Christian's answer shows how to do this.

但是,您的最终目标是根据一些用户输入(在您的情况下为音频)更新 TextView,您不必跳过所有这些循环即可使其正常工作.唯一重要的是您在 UI 线程上发布更新 UI 的调用,否则会出现异常.

However, seeing as your final goal is to update the TextView based on some user input (audio in your case) you won't have to jump through all these loops to make it work. The only important thing is that you post your calls to update the UI on the UI thread, otherwise you'll get exceptions.

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

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