问题描述
我要更新的TextView
从Android应用程序的异步任务。什么是用最简单的方式处理程序
?
I want to update a TextView
from an asynchronous task in an Android application. What is the simplest way to do this with a Handler
?
有一些类似的问题,比如这个:的Android更新的TextView与处理程序的,但该实施例很复杂,没有出现应答。
There are some similar questions, such as this: Android update TextView with Handler, but the example is complicated and does not appear to be answered.
推荐答案
有几种方法来更新你的用户界面,并修改查看
如的TextView
从UI线程之外。 A 处理程序
只是其中的一个方法。
There are several ways to update your UI and modify a View
such as a TextView
from outside of the UI Thread. A Handler
is just one method.
下面是一个例子,它允许一个单一的处理程序
应对多种类型的请求。
Here is an example that allows a single Handler
respond to various types of requests.
在类级别定义一个简单的处理程序
:
At the class level define a simple 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,在您的功能之一,这是现在在UI线程:
Update the UI in one of your functions, which is now on the UI Thread:
private void doUpdate() {
myTextView.setText("I've been updated.");
}
这是在你的异步任务,发送邮件到处理程序
。有几种方法可以做到这一点。这可能是最简单的:
From within your asynchronous task, send a message to the Handler
. There are several ways to do it. This may be the simplest:
myHandler.sendEmptyMessage(DO_UPDATE_TEXT);
这篇关于如何使用一个机器人处理程序更新UI线程一个TextView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!