GridLayout 共享元素转换无法正常工作

GridLayout shared element transition not working correctly

我正在尝试在 RecyclerViewGridLayoutManager 和片段之间创建过渡。网格显示用户图片缩略图,当我点击缩略图时,它会显示用户的详细信息。但是,当我点击缩略图并显示详细信息时,过渡总是从屏幕的左上角而不是缩略图位置开始。

如何让过渡从缩略图位置开始?

这是我想要的结果:

这就是我得到的:

这是我的代码:

// UsersAdapter.kt
override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
        ViewCompat.setTransitionName(holder.itemView.picture, "picture_$position")
}

// MasterFragment.kt
// This is called when i click an item in the grid
itemClickSubject.subscribe { position ->
        val user = users[position]
        val transitionName = "picture_$position"

        fragmentManager
                ?.beginTransaction()
                ?.addSharedElement(picture, transitionName)
                ?.replace(R.id.content, DetailsFragment.create(user, transitionName))
                ?.addToBackStack(null)
                ?.commit()
    }.addTo(disposables)

// DetailsFragment.kt
class DetailsFragment : Fragment() {

    companion object {

        fun create(user: User, transitionName: String): DetailsFragment {
            val args = Bundle()
            args.putParcelable("user", user)
            args.putString("transition_name", transitionName)

            val fragment = DetailsFragment()
            fragment.arguments = args

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {                   
                fragment.sharedElementEnterTransition = ChangeBounds()
                fragment.sharedElementReturnTransition = ChangeBounds()
            }

            return fragment
        }

    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_details, container, false).apply {
            val transitionName = arguments?.getString("transition_name", "")
            ViewCompat.setTransitionName(findViewById(R.id.picture), transitionName)
        }
    }

}

根据您共享的代码,假设您共享了所有添加的与共享元素转换相关的代码,我相信您会错过推迟和恢复共享元素转换调用。

The images we would like to transition are loaded into the grid and the pager and take time to load. To make it work properly, we will need to postpone the transition until the participating views are ready (e.g. laid out and loaded with the image data).

To do so, we call a postponeEnterTransition() in our fragments' onCreateView(), and once the image is loaded, we start the transition by calling startPostponedEnterTransition().

Note: postpone is called for both the grid and the pager fragments to support both forward and backward transitions when navigating the app.

https://android-developers.googleblog.com/2018/02/continuous-shared-element-transitions.html

用于更深入解释的额外资源:

https://www.androiddesignpatterns.com/2015/03/activity-postponed-shared-element-transitions-part3b.html