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

时间:2016-03-16 23:41:57

标签: android android-fragments android-transitions fragmentmanager

我有两个片段--A和B - 两个片段占据整个屏幕。当我加载我的活动时,我在后台显示用户片段A我加载片段B(在fragmentmanager中我在片段A上替换然后在片段B上我添加和隐藏)。两个片段都有相对相似的布局(或者至少可以说,转换前的A的布局类似于B的起始布局 - 视图移动)当我想从A移动到BI时在B上“显示”并在A上“隐藏”它几乎完美无缺,但在B显示之前,你仍然可以看到中间有一段白色的短暂闪现,并且它会破坏两者都是相同片段的错觉。如果没有用户注意,我该如何转换?

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

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

•正如我上面所说,我尝试在后台添加B,只在需要时对其进行“显示” - 以节省任何设置时间

•我尝试覆盖待处理的转换并添加淡出/淡出,但没有区别

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

•我尝试用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();

2 个答案:

答案 0 :(得分:1)

您是否尝试为FragmentTransaction设置TRANSIT_NONE?

  

TRANSIT_NONE没有过渡动画。

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

// 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

答案 1 :(得分:1)

mMapFragment = new MapFragment();

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