Android:如何在用户不注意的情况下从一个片段移动到另一个片段?

Android: how to move from one fragment to another without the user noticing?

我有两个片段 - A 和 B - 两个片段都占据了整个屏幕。当我加载我的 activity 我显示用户片段 A,而在后台我加载片段 B(在片段管理器中我在片段 A 上替换,然后在片段 B 上我添加和隐藏)。这两个片段都有相对相似的布局(或者至少可以公平地说,过渡之前 A 的布局类似于 B 的起始布局——视图四处移动),当我想从 A 移动到 B 时,我做了一个B 上的 "show" 和 A 上的 "hide"。它几乎可以完美运行,但在显示 B 之前,您仍然可以看到两者之间有短暂的白色闪光,这破坏了两者是同一片段的错觉.如何在用户不注意的情况下进行转换?

关于为什么有两个片段而不是一个片段的解释几句话 - 业务逻辑是分开的。每个片段处理流程的不同部分,将它们组合起来没有任何意义。

到目前为止我尝试过的事情:

• 正如我上面所说,我尝试在后台添加 B 并仅在需要时对其执行 "show" - 以节省任何设置时间

• 我尝试覆盖挂起的转换并放置 fadeout/fadein,但没有任何区别

• 我尝试在显示 fragmentB 时隐藏 fragmentA 而不是将其删除,但没有任何区别

• 我尝试用 0,0 覆盖挂起的过渡(完全摆脱过渡),但它仍然是一样的

代码:

getSupportFragmentManager().beginTransaction()
            .replace(R.id.contentBlock, fragmentA, "FRAGMENTA")
            .add(R.id.contentBlock, fragmentB)
            .hide(fragmentB)
            .commit();

及以后:

getSupportFragmentManager().beginTransaction()
            .show(fragmentB)
            .remove(fragmentA)
            .commit();

您是否尝试过为 FragmentTransaction 设置 TRANSIT_NONE?

TRANSIT_NONE No animation for transition.

此外,考虑到您只是将一个片段替换为另一个片段,我建议使用 replace,如下例所示:

// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(R.id.fragment_container, newFragment);
transaction.setTransition(FragmentTransaction.TRANSIT_NONE);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

注意:XML 中硬编码的片段无法替换。 (如所述here

mMapFragment = new MapFragment();

ft.beginTransaction(mMapFragment) .detach(getactivity) .attach(mMapFragment) .commit();