Update Android UI from a thread in another class

前端 未结 3 663
轮回少年
轮回少年 2021-02-11 01:01

I\'ve seen a few questions on here asking similar questions, but I\'ve not yet seen a suitable answer. Many people have asked how to update the UI from a thread, but they\'re al

3条回答
  •  孤街浪徒
    2021-02-11 01:27

    There are a couple of options. If you have access to the View you are changing and simply need to force a refresh, you can use View.postInvalidate() from any thread. If you need more complex operations, such as changing the text of a button, you should use runOnUIThread, which requires access to the Activity context. This should be simple to get - just add it as a parameter for your custom Object's constructor. With this context, you can do something like this:

    activityContext.runOnUiThread(new Runnable(){
        @Override
        public void run() {
            myButton.setText("disconnect");
        }
    });
    

提交回复
热议问题