Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

How to use an Android Handler to update a TextView in the UI Thread?

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?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
        }
    }
};

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...