android - adding views is too slow

有些话、适合烂在心里 提交于 2019-12-13 00:51:07

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/31298223/android-adding-views-is-too-slow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!