目标:实现图片的放大至全屏,缩小至原图的动画效果
MainActivity中有两个fragment,firstFragment和secondFragment。
1.在res/transition中定义changebounds.xml文件
<?xml version="1.0" encoding="utf-8"?>
<changeBounds xmlns:android="http://schemas.android.com/apk/res/android">
</changeBounds>
2.在MainActivity中加载firstFragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportFragmentManager.beginTransaction().add(R.id.root, FirstFragment.newInstance(), "1")
.addToBackStack(null)
.commit()
}
3.分别在fragment_first.xml和fragment_second.xml中图片设置android:transitionName="@string/transition"属性
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FirstFragment">
<ImageView
android:id="@+id/iv_img"
android:layout_width="100dp"
android:layout_height="100dp"
android:transitionName="@string/transition"
android:src="@mipmap/ic_launcher" />
</FrameLayout>
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondFragment">
<ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@mipmap/ic_launcher"
android:transitionName="@string/transition"/>
</FrameLayout>
4.在firstFragment中点击图片实现跳转
iv_img.setOnClickListener {
val mainActivity = activity as MainActivity
mainActivity.supportFragmentManager.beginTransaction()
.replace(R.id.root, SecondFragment.newInstance(), "2")
.addToBackStack(null)
.setReorderingAllowed(true)
.addSharedElement(iv_img, getString(R.string.transition))
.commit()
}
5.在secondFragment中使用
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
sharedElementEnterTransition = TransitionInflater.from(context).inflateTransition(R.transition.changebounds)
}