1

I need to add about 10 views to ScrollView and I use the following code

final LinearLayout item_div = (LinearLayout)activity.findViewById(R.id.item_div);
final LayoutInflater inflater = (LayoutInflater)context.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < itemArray.length(); i++) {
   View itemTemplate = inflater.inflate(R.layout.item, null);
   item_div.addView(itemTemplate);
}

but the problem is that this process take about 1-2 seconds and it blocks the main UI, and the waiting is not from fetching data from server, it comes directly from just adding the view(they are a little heavy). Now my question is, can I use a new thread or background service to do this? Can any kind of thread or background task handle this type of view problem or it's pointless to do it in the background and I should consider RecyclerView or some other solutions? thank you

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
Mohsen Shakiba
  • 1,762
  • 3
  • 22
  • 41

3 Answers3

0

can I use a new thread or background service to do this

No, you cannot touch your UI from background threads or exception will be thrown

or it's pointless to do it in the background and I should consider recyclerview or some other solutions

Not seeing the whole purpose of the approach you took it's hard to give any answer, but if you just need scrollable container RecyclerView may give the hand. Also, maybe you got just finite number of combination of your child views you need to show, you may consider preparing combined layouts and then just inflate one instead of doing 10 separate inflations. Other approach would be to create your child views from code but I'd leave it as last option to check.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
0

Turned out the best way to handle my problem was to use ListView with Adapeter or even better(but also harder) would be to user RecycleView. any way I managed to get a pretty decent performance on my list by using the ListView

Mohsen Shakiba
  • 1,762
  • 3
  • 22
  • 41
  • out of curiosity: how this really differs from the option I mentioned in my, formerly accepted answer that you revoked the accept? – Marcin Orlowski Jul 09 '15 at 16:46
  • you gave me a bunch of solutions but only the recycle was the answer, I thought for future readers mine would be more clear. but fine, I'll change it back to what it was. – Mohsen Shakiba Jul 09 '15 at 17:22
0

I was able to do this by running the inflating view inside AsynTask or with using Concurrent API as my scenario of having accordion/collapsing list of list is not good for RecyclerView ViewHolder pattern having too many frame skip due to the UI being block when adding view in LinearLayout programmatically . See my answer here it may give you some idea https://stackoverflow.com/a/65741410/12204620

Bitwise DEVS
  • 2,858
  • 4
  • 24
  • 67