Search code examples
androidviewandroid-inflate

android - adding views is too slow


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


Solution

  • 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.