Running a method on UI thread

吃可爱长大的小学妹 提交于 2019-12-13 06:35:28

问题


My question seems very simple but i can't seem to the logic right. Am trying to run methods from other classes using the UI thread. I could do this this simply by wrapping my methods like this

    runOnUiThread(new Runnable() {
    public void run() {
        Log.d("UI thread", "I am the UI thread");
           ui.myMethod("changetext");
    }
});

but my goal is to have a class that wraps methods to be run on the UI thread as having runOnUiThread() almost 5 times in a single class seems very untidy. Any pointers?


回答1:


If you're calling the same UI method repeatedly, you could streamline the client code by creating the Runnable in a method:

private void updateUi(final String message) {
   runOnUiThread(new Runnable() {
      public void run() {
         ui.myMethod(message);
      }
   });
}

Then your client code would simply call updateUi("changetext"). (This code assumes that ui is final. If not, you could pass in a final reference.)

If you're calling a different UI method every time, this doesn't gain you anything as you'd need a separate update method for each UI method. Your existing code is as elegant as it gets.




回答2:


If you really have to do this from multiple classes, you could create a public static method that will run a runnable on the main thread. Something like this:

public class Util {
    public static void runOnUI(Activity a, Runnable r){
        a.runOnUIThread(r);
    }
}

You call it by doing something like this:

Util.runOnUI(getActivity(), mRunnable);


来源:https://stackoverflow.com/questions/31217690/running-a-method-on-ui-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!