如何刷新一个TextView,而在Android的循环?而在、TextView、Android

2023-09-12 09:41:22 作者:哥ㄣ闪亮登场

我有这样的:

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的循环过程中刷新。我是新的Andr​​oid开发。有谁能告诉我,如果这是实现这一目标的最佳方式是什么?

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你的循环()。这是发生在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中的活动周期。它显示的onCreate仅仅是阶段的活动创造之一。什么,你会想要做的是运行在后台线程的循环,并张贴通知,以更新的TextView到使用runOnUiThread UI线程。基督教的回答显示了如何做到这一点。

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线程上的用户界面,否则你会得到异常。

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.