9

I need to add lots of views in a loop, while this fragment does that, the app will also have a navigation drawer and action bar where the user can do things.

so I would like this process to not a) slow down the app by blocking the user, b) preferably add the views in a background thread.

The dilemma is that I think android doesn't like views to be added in a non-UI thread, so is there a best practice for this? I plan to have a progress bar view object visible in the fragment's view while the rest of the views are being generated with the addView and associated computations

CQM
  • 42,592
  • 75
  • 224
  • 366
  • Can you elaborate on what you are doing? ie, what kind of views you are adding? My guess is that some adapterview variation will work. – JoeyG Sep 25 '13 at 19:57
  • 2
    "is there a best practice for this?" -- not have "lots of views" in the first place. – CommonsWare Sep 25 '13 at 20:49

1 Answers1

23

Instead of adding view on a background thread you can parcel out the work by posting several Runnables on the UI thread. The code below is a highly simplified version of that technique but it's similar to how it was done in Android's Launcher app:

private void createAndAddViews(int count) {
    for (int i = 0; i < count; i++) {
         // create new views and add them
    }
}

Runnable r = new Runnable() {
    public void run() {
        createAndAddViews(4); // add 4 views
        if (mMoreViewsToAdd) mTopLevelView.post(this);
    }
};

mTopLevelView.post(r);
Prateek
  • 3,923
  • 6
  • 41
  • 79
Romain Guy
  • 97,993
  • 18
  • 219
  • 200
  • 2
    I don't get it Sir. . . I got 5 LinearLayouts to populate with lots of items.. how do I add Views that will not make my ProgressBar whic is visible during before the runnable is finished to not lag. – Sheychan Oct 01 '15 at 10:49
  • Great way draw complex UI. – Bek Feb 12 '20 at 09:54