Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ProgressBar not animating while inflating viewstub

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?

like image 951
MariusBudin Avatar asked Jul 23 '14 12:07

MariusBudin


2 Answers

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.

like image 62
EE66 Avatar answered Nov 15 '22 05:11

EE66


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.

like image 43
Eshaan Avatar answered Nov 15 '22 05:11

Eshaan