Is a Fragment on the UIThread?

554 views Asked by At

When I first started my project, I updated the UI from all over the place. This worked for a while, because only a Seekbar was being updated from a worker thread and for some reason that worked. I then updated a TextView from the same worker thread and it crashed my app, so I started calling runOnUIThread(new Runnable(){...}); every time I needed to update the UI from a worker thread.

My Fragments also need to update the UI and they update their own UI elements as well as the Activity elements with no errors.

Should I be using runOnUIThread(new Runnable(){...}); in Fragments to update UI elements or are the Fragments on the UI thread?

1

There are 1 answers

1
Hamza Sharaf On

The fragment itself as an object is not a part of the UI. However, the root view of the fragment is a part of this UI. What I mean is that the view you are returning back from the onCreateView() method is representing your UI and if you need to update any element in this view such as TextViews or Buttons from any other thread, you definitely have to use runOnUIThread(new Runnable(){...}); method.

Remark

If you are using RxJava or Coroutines this operation will be much easier for you as it makes switching threads very easy.