我遵循了here的说明。
这是我的代码:
val navDirections = PostsListFragmentDirections.actionPostsListFragmentToPostDetailFragment(post)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val animationExtras = FragmentNavigatorExtras(
title to title.transitionName,
body to body.transitionName
)
navigateWithAnimations(navDirections, animationExtras)
} else {
navigateTo(navDirections)
}
[navigateTo
和navigateWithAnimations
是扩展功能:
fun Fragment.navigateTo(navDirections: NavDirections) {
NavHostFragment.findNavController(this).navigate(navDirections)
}
fun Fragment.navigateWithAnimations(navDirections: NavDirections, extras: Navigator.Extras) {
NavHostFragment.findNavController(this).navigate(navDirections, extras)
}
正在执行代码,但动画不起作用。
这里是nav_graph.xml
<fragment
android:id="@+id/postsListFragment"
android:name="PostsListFragment"
android:label="PostsListFragment">
<action
android:id="@+id/action_postsListFragment_to_postDetailFragment"
app:destination="@id/postDetailFragment">
<argument
android:name="post"
app:argType="Post"
app:nullable="true"
android:defaultValue="@null" />
</action>
</fragment>
<fragment
android:id="@+id/postDetailFragment"
android:name="PostDetailsFragment"
android:label="PostDetailFragment">
<argument
android:name="post"
app:argType="Post"
app:nullable="true"
android:defaultValue="@null" />
</fragment>
这是将视图设置为第二个(目标片段)的方法:
private val args: PostDetailsFragmentArgs by navArgs()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
args.post?.let { post ->
tv_title.text = post.title
tv_body.text = post.title
}
}
在我定义的两个XML文件中:
android:transitionName="transition_title"
android:transitionName="transition_body"
您是否在第二个片段中建立了sharedElementEnterTransition属性?您必须在onCreate方法中执行以下操作:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
main = requireActivity() as MainActivity
sharedElementEnterTransition = ChangeBounds().apply {
duration = 750
interpolator = AccelerateDecelerateInterpolator()
}
sharedElementReturnTransition = ChangeBounds().apply {
duration = 750
interpolator = AccelerateDecelerateInterpolator()
}
}
换句话说,接收片段需要知道如何处理共享元素。