逐个加载多个片段

时间:2016-08-10 10:13:42

标签: android android-layout android-fragments android-bundle

我必须填充一个包含多达100个不同片段的活动来遍历我正在使用for循环的所有片段,但不是一个接一个地添加片段,而是一次性添加所有片段。直到那发生应用冻结,有时冻结4-5秒。如何逐个加载它们? 以下是我到目前为止所做的事情......

for (i = 0; i < combofinalist.size(); i++) {
    Bundle c = new Bundle();
    fm = getSupportFragmentManager();
    ft = fm.beginTransaction();
    combofrag combofrag = new combofrag();
    int fragdata = combofinalist.get(i);
    c.putInt("combonum", fragdata);
    c.putInt("editable", 1);
    combofrag.setArguments(c);
    ft.replace(combolayouts[y], combofrag, "combo" + y);
    y = y + 1;
    ft.commit();
}

2 个答案:

答案 0 :(得分:0)

替换片段后放置延迟

您可以使用处理程序来延迟

答案 1 :(得分:0)

尝试为每次添加运行新线程:

fm = getSupportFragmentManager(); 
for (i = 0; i < combofinalist.size(); i++) { 
    new Thread(new Runnable() {
        @Override
        public void run() {
            ft = fm.beginTransaction(); 
            combofrag combofrag = new combofrag();
            int fragdata = combofinalist.get(i);
            Bundle c = new Bundle();
            c.putInt("combonum", fragdata);
            c.putInt("editable", 1);
            combofrag.setArguments(c);
            ft.replace(combolayouts[y], combofrag, "combo" + y);
            y = y + 1; 
            ft.commit(); 
        }
    }).run();
} 

修改

通过FragmentManager.class读取commit()状态的注释:

/**
     * After a {@link FragmentTransaction} is committed with
     * {@link FragmentTransaction#commit FragmentTransaction.commit()}, it
     * is scheduled to be executed asynchronously on the process's main thread.
     * If you want to immediately executing any such pending operations, you
     * can call this function (only from the main thread) to do so.  Note that
     * all callbacks and other related behavior will be done from within this
     * call, so be careful about where this is called from.
     *
     * @return Returns true if there were any pending transactions to be
     * executed.
     */

在安排时,我只能假设所有交易都是立即提交的。您可以尝试向线程添加延迟,或者如果您有权访问Context,可以尝试runOnUiThread()。但是无法想象这会对性能有所帮助。