后台线程中的android addView [英] android addView in background thread

查看:17
本文介绍了后台线程中的android addView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在循环中添加大量视图,而这个片段可以做到这一点,应用程序还将有一个导航抽屉和操作栏,用户可以在其中做一些事情.

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.

所以我希望这个过程不会 a) 通过阻止用户来减慢应用程序的速度,b) 最好在后台线程中添加视图.

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.

问题在于,我认为 android 不喜欢在非 UI 线程中添加视图,那么对此有最佳实践吗?我计划在片段视图中显示一个进度条视图对象,而其余的视图正在使用 addView 和相关计算生成

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

推荐答案

您可以通过在 UI 线程上发布多个 Runnable 来分配工作,而不是在后台线程上添加视图.下面的代码是该技术的高度简化版本,但它类似于在 Android 的 Launcher 应用中的实现方式:

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

这篇关于后台线程中的android addView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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