How to use shared element transitions in Navigation Controller

前端 未结 9 726
醉话见心
醉话见心 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:31

    To make this work from a recyclerView's ImageView the setup everything like the following:

    val adapter = PostAdapter() { transitionView, post ->
        findNavController().navigate(
            R.id.action_postsFragment_to_postsDetailFragment,
            null,
            null,
            FragmentNavigatorExtras(transitionView to getString(R.string.transition_image)))
    }
    

    within the adapter this does the trick:

    itemView.setOnClickListener {
        ViewCompat.setTransitionName(imageView, itemView.context.getString(R.string.transition_image))
        onClickedAction?.invoke(imageView, post)
    }
    

    You don't have to specify the transition name within the adapter's item's xml but simply set it from code as soon as the item gets clicked.

    The onClickedAction looks like:

    private val onClickedAction: ((transitionView: View, post: Post) -> Unit)?
    

    and you pass it to your ViewHolder.

    In the second Fragment you set the transition name to the ImageView in xml:

    android:transitionName="@string/transition_image"
    

    and assign the transition like

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val transition = TransitionInflater.from(context).inflateTransition(android.R.transition.move)
        sharedElementEnterTransition = transition
        sharedElementReturnTransition = transition
    }
    

提交回复
热议问题