如何在安卓棒棒糖系统中延迟一个Fragment的进入动画?

17
2个回答

13

在Fragment转换中,没有直接的等效项,因为Fragment使用FragmentTransaction,我们无法真正推迟在事务中应该发生的事情。

要获得等效项,您可以在事务中添加一个Fragment并将其隐藏起来,然后当该Fragment准备就绪时,从事务中删除旧Fragment并在事务中显示新Fragment。

getFragmentManager().beginTransaction()
    .add(R.id.container, fragment2)
    .hide(fragment2)
    .commit();

稍后,当fragment2准备好时:

getFragmentManager().beginTransaction()
    .addSharedElement(sharedElement, "name")
    .remove(fragment1)
    .show(fragment2)
    .commit();

不错,但是我们在fragment2完成并调用FragmentManager.popBackStack()后,如何推迟fragment1的设置呢? - mennovogel
如果您不删除fragment1,而是将其隐藏,那么这将使您的生活更加轻松。否则,需要额外的步骤,但它的工作方式相同。a)添加2,隐藏2 b)显示2,隐藏,添加到后退堆栈1 c)显示1,删除1,添加到后退堆栈。然后,当您第二次到达(c)时,等待1准备好,然后以编程方式弹出后退堆栈。 - George Mount
@GeorgeMount 我在我的片段转换中遇到了问题(如我的SO问题所述)。开始认为这是因为我的片段在动画开始时还没有准备好。在您上面的评论中,我理解步骤a)和b),但是“c)显示1、删除1、添加到后退堆栈。然后,您检测到第二次到达(c)时,等待1准备就绪,然后以编程方式弹出后退堆栈。”有点让我困惑。您能详细说明一下吗? - Sound Conception
希望这可以帮到你:https://halfthought.wordpress.com/2015/06/04/postponing-fragment-transitions/ - George Mount
你说过等片段准备好后再进行,那么你如何知道何时会发生这种情况? - user3497504
显示剩余5条评论

3
您可以通过以下方式推迟Fragment的进入转换:

您可以通过以下方式推迟Fragment的进入转换:

  • Allow FragmentTransaction to re-order & optimize the transaction

    requireActivity().supportFragmentManager
      .beginTransaction()
      .replace(R.id.container, fragmentB)
      .addSharedElement(view, "transitionName")
      .setReorderingAllowed(true) // Set to true
      .commit()
    
  • Tell fragmentB to delay the transition after view creation

    class TransitionToFragment : Fragment(R.layout.fragment_b) {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
      super.onViewCreated(view, savedInstanceState)
      postponeEnterTransition() // Don't start enter transitions yet!
    
      ... // Setup your views
    
      (view.parent as? View)?.doOnPreDraw { startPostponedEnterTransition() } // Ok, start transitions
    }
    }
    

    view.parent.doOnPreDraw { ... } is used to ensure the fragment's views are measured and laid out for the transition. See Chris Banes's blog for more details.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接