android - 添加视图太慢 [英] android - adding views is too slow

查看:39
本文介绍了android - 添加视图太慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要向 ScrollView 添加大约 10 个视图,我使用以下代码

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);
}

但问题是这个过程大约需要 1-2 秒,它阻塞了主 UI,等待不是从服务器获取数据,它直接来自添加视图(它们有点重).现在我的问题是,我可以使用新线程或后台服务来执行此操作吗?任何类型的线程或后台任务都可以处理这种类型的视图问题,或者在后台执行它毫无意义,我应该考虑 RecyclerView 或其他一些解决方案吗?谢谢

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

推荐答案

我可以使用新线程或后台服务来执行此操作吗

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

不,您不能从后台线程触摸您的 UI,否则将引发异常

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

或者在后台做没有意义,我应该考虑recyclerview或其他一些解决方案

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

没有看到您采用的方法的全部目的,很难给出任何答案,但是如果您只需要可滚动容器 RecyclerView 可能会提供帮助.此外,也许您需要显示的子视图组合数量有限,您可以考虑准备组合布局,然后只对一个进行充气,而不是进行 10 次单独的充气.其他方法是从代码创建您的子视图,但我将其作为最后一个检查选项.

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.

这篇关于android - 添加视图太慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆