android目前只支持两个页面跳转时使用共享元素,如果是三个页面间跳转,中间的页面会丢失共享元素信息,如a -> b >c , c返回b后,此时b的共享元素丢失,造成b返回a时,共享元素返回动画无法执行。
解决:
oncreate保存共享元素:
var sharedElementList: List<String>? = null
//保存shared element
setEnterSharedElementCallback(object : SharedElementCallback() {
override fun onSharedElementsArrived(sharedElementNames: MutableList<String>?, sharedElements: MutableList<View>?, listener: OnSharedElementsReadyListener?) {
super.onSharedElementsArrived(sharedElementNames, sharedElements, listener)
sharedElementList = sharedElementNames?.toList()
}
})
onResume重建共享元素:
@SuppressLint("PrivateApi")
fun updateResume(activity: Activity ){
try {
val activityTransitionStateField: Field = Activity::class.java.getDeclaredField("mActivityTransitionState");
activityTransitionStateField.isAccessible = true
val mActivityTransitionState = activityTransitionStateField.get(activity)
val activityTransitionStateClazz =
Class.forName("android.app.ActivityTransitionState")
val exitNameField = activityTransitionStateClazz.getDeclaredField("mPendingExitNames")
exitNameField.isAccessible = true
exitNameField.set(mActivityTransitionState, sharedElementList)
} catch (e: Exception) {
Log.d(Tag, "exception: "+ e.message)
}
}
目前没有发现问题,但其实最好用fragment来构建页面b、c来解决该问题,但是实践中b、c用frament后共享元素动画不及预期,同样的transtion,fragment的效果表现像bug一样,最终还是使用了反射方案,线上目前没有收到问题反馈。
网友评论