所以我有一个动画视图,我想在动画完成后返回到屏幕的中心。我使用此代码将视图的中心置于屏幕中心:
val screencenterX = (FullscreenActivity.metrics.widthPixels - mContentView.width) / 2
val screencenterY = (FullscreenActivity.metrics.heightPixels - mContentView.height) / 2
val soultostartx = ObjectAnimator.ofFloat(mContentView, "x", screencenterX.toFloat()).apply {
duration = 1
}
val soultostarty = ObjectAnimator.ofFloat(mContentView, "y", screencenterY.toFloat()).apply {
duration = 1
}
fun toStart() = AnimatorSet().apply {
play(soultostartx).with(soultostarty)
start()
}
toStart()
这在纵向模式下工作正常,但是一旦手机旋转到横向,相关视图就会移动到屏幕左下角的某个位置。知道为什么会这样吗?获取屏幕中心的数学应该是否相同?
之所以发生这种情况,是因为当您重新启动手机时,您应该在活动中覆盖此方法:
@Override
public void onConfigurationChanged(Configuration myConfig)
{
super.onConfigurationChanged(myConfig);
int orient = getResources().getConfiguration().orientation;
switch(orient)
{
case Configuration.ORIENTATION_LANDSCAPE: setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
case Configuration.ORIENTATION_PORTRAIT:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
default:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}
不要忘记将android:configChange:"orientation|screenSize"
添加到清单中的活动标签
编辑
kotlin:check this tuto