I have an Activity with this structure:
FrameLayout
ProgressBar
ViewStub
The ViewStub inflates a Fragment in a separate thread. What I need is to display the progress while the fragment loads. The problem is the ProgressBar is not spinning while the stub inflates (in my case about half a second: it's a heavy fragment) I've tried everything: showing/hiding the view, invalidate, show them in ViewSwitchers...etc, nothing works, as soon as the ViewStub inflates, it starts spinning, it's like the ui is frozen while it inflates but doing it in another thread doesn't seem to improve. What should I do?
The fragment must be loaded on the UI thread, and because the UI is busy with the fragment the ProgressBar doesnt spin. You need to seperate the data loading in the fragment to the UI stuff. I would test and check what exactly is running and keeping the fragment from starting up fast , i would use a loader in order to load the data while presenting a progressbar to the user (inside the fragment) . Yes, move the progress to the layout of the fragment and control everything from there because i dont the activity to know when the fragment is done loading, the activity doesnt suppose to care about that.
Basically what @Luksprog said in his comment is correct if you call viewStub.post() this does NOT run the code inside the post on a background thread. All it does is post the runnable to the UI thread. It may work if you do
new Thread(new Runnable() {
@Override
public void run() {
viewStub.inflate();
initFragment();
}
}).start()
Although as @Luksprog also stated - it's bad practice to instantiate views on a background thread. So perhaps the best solution is to move the .inflate() call outside (onto the main thread), and then call initFragment() from the background thread and put all the heavy lifting in there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With