如何使用Android Handler在UI线程中更新TextView?

9

我希望在 Android 应用程序中的异步任务中更新 TextView。使用 Handler 最简单的方法是什么?

有一些类似的问题,例如这个:Android update TextView with Handler,但是示例比较复杂,而且似乎没有得到答案。

2个回答

22

有几种方法可以在UI线程外部更新您的UI并修改一个View,例如TextViewHandler只是其中一种方法。

这里有一个示例,允许单个Handler响应各种类型的请求。

在类级别定义一个简单的Handler

private final static int DO_UPDATE_TEXT = 0;
private final static int DO_THAT = 1;
private final Handler myHandler = new Handler() {
    public void handleMessage(Message msg) {
        final int what = msg.what;
        switch(what) {
        case DO_UPDATE_TEXT: doUpdate(); break;
        case DO_THAT: doThat(); break;
        }
    }
};

在你的某个函数中更新用户界面,该函数现在在UI线程上:

private void doUpdate() {
    myTextView.setText("I've been updated.");
}

在异步任务内部,向Handler发送一条消息。有几种方法可以做到这一点。可能最简单的方法是:

myHandler.sendEmptyMessage(DO_UPDATE_TEXT);

5
Handler class should be static otherwise memory leaks might occur 警告是什么意思? - nmxprime
1
请查看博客文章和这个答案(https://dev59.com/T2gu5IYBdhLWcg3wUlnt),以获取更多关于此问题的见解。 - Renjith K N
我建议在这里使用WeakHandler以避免泄漏。https://github.com/badoo/android-weak-handler - j2emanue

4
您也可以通过以下方式从后台线程更新UI线程:

您也可以通过以下方式从后台线程更新UI线程:

Handler handler = new Handler(); // write in onCreate function

//below piece of code is written in function of class that extends from AsyncTask

handler.post(new Runnable() {
    @Override
    public void run() {
        textView.setText(stringBuilder);
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接