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

前端 未结 2 1334
星月不相逢
星月不相逢 2020-11-30 07:11

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

相关标签:
2条回答
  • 2020-11-30 07:40

    You can also update UI thread from background thread in this way also:

    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);
        }
    });
    
    0 讨论(0)
  • 2020-11-30 07:50

    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);
    
    0 讨论(0)
提交回复
热议问题