How do we use runOnUiThread in Android?

前端 未结 12 919
太阳男子
太阳男子 2020-11-22 00:09

I\'m new to Android and I\'m trying to use the UI-Thread, so I\'ve written a simple test activity. But I think I\'ve misunderstood something, because on clicking the button

12条回答
  •  孤城傲影
    2020-11-22 00:59

    Try this: getActivity().runOnUiThread(new Runnable...

    It's because:

    1) the implicit this in your call to runOnUiThread is referring to AsyncTask, not your fragment.

    2) Fragment doesn't have runOnUiThread.

    However, Activity does.

    Note that Activity just executes the Runnable if you're already on the main thread, otherwise it uses a Handler. You can implement a Handler in your fragment if you don't want to worry about the context of this, it's actually very easy:

    // A class instance

    private Handler mHandler = new Handler(Looper.getMainLooper());
    

    // anywhere else in your code

    mHandler.post();
    

    // ^ this will always be run on the next run loop on the main thread.

提交回复
热议问题