How to use shared element transitions in Navigation Controller

前端 未结 9 549
醉话见心
醉话见心 2021-01-31 08:06

I would like to add a shared elements transition using the navigation architecture components, when navigating to an other fragment. But I have no idea how. Also in the document

9条回答
  •  庸人自扰
    2021-01-31 08:45

    So let's say that you have two Fragments, FragmentSecond and FragmentThird. Both have ImageView with the same transitionName, let's say : "imageView"

    android:transitionName="imageView"
    

    Just define a normal action between these fragments.

    In FragmentSecond, let's add our extras

    val extras = FragmentNavigatorExtras( binding.image to "imageView")
    
    findNavController().navigate(R.id.action_secondFragment_to_thirdFragment , null, null , extras)
    

    So we're saying that we want to share that ImageView, with that transitionName, with ThirdFragment

    And then in ThirdFragment :

    override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            sharedElementEnterTransition = TransitionInflater.from(context).inflateTransition(android.R.transition.move)
            setHasOptionsMenu(true)
        }
    
        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            Glide.with(this).load(IMAGE_URI).into(binding.headerImage)
        }
    

    The only thing that we have to do is load the image in the two fragments from the same URL. The URL can be passed between fragments using a Bundle Object and pass it in the navigate call or as a destination argument in the navigation graph.

    If you need it, i am preparing a sample about Navigation and there's SharedElementTransition too :

    https://github.com/matteopasotti/navigation-sample

提交回复
热议问题