如何在屏幕旋转等动画后保留 activity 的状态?
How to retain state of activity after animation upon something like screen rotation?
因此,例如,我使用对象动画师将按钮的 alpha 更改为 0,然后旋转屏幕,然后它返回到动画前状态,因为再次调用了 onCreate。我在想我应该实现类似动画侦听器的东西,并且在动画结束时我应该更改按钮的属性,但我不确定该怎么做。例如,如果我有一个约束布局并且我将一个按钮向上移动了 100 个像素,我应该在动画侦听器中包含什么代码以便在动画结束后保留更改。我阅读了一些关于将标记后的填充设置为 true 的内容,但我相信这是针对视图动画的。
感谢您的帮助。
对于您描述的应用程序,您可以使用 ValueAnimator
并在其上设置 AnimatorUpdateListener
以记录每个动画帧之后的状态。
要监听方向变化并保持动画状态,您应该首先在清单的 <activity>
标记中包含 android:configChanges="orientation"
。这将确保您的 activity 不会在方向更改时重新创建,并且不会再次调用 onCreate()
。每当发生方向更改时,都会调用 onConfigurationChanged()
,因此您应该覆盖它以保持动画状态。
因此,在您的 onCreate()
中,您可以执行以下操作:
ValueAnimator valueAnimator = ValueAnimator.ofObject(new IntEvaluator(),
initialPosition, finalPosition);
valueAnimator.setDuration(duration);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
// mCurrentPosition should be a member variable
mCurrentPosition = (int)animation.getAnimatedValue();
// Update the position of your button with currentPosition
}
}
valueAnimator.start();
你的 onConfigurationChanged()
应该是这样的:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.your_layout);
// Set the position of your button with mCurrentPosition
}
更多信息,请参考https://developer.android.com/reference/android/animation/ValueAnimator.html and https://developer.android.com/guide/topics/resources/runtime-changes.html。
因此,例如,我使用对象动画师将按钮的 alpha 更改为 0,然后旋转屏幕,然后它返回到动画前状态,因为再次调用了 onCreate。我在想我应该实现类似动画侦听器的东西,并且在动画结束时我应该更改按钮的属性,但我不确定该怎么做。例如,如果我有一个约束布局并且我将一个按钮向上移动了 100 个像素,我应该在动画侦听器中包含什么代码以便在动画结束后保留更改。我阅读了一些关于将标记后的填充设置为 true 的内容,但我相信这是针对视图动画的。
感谢您的帮助。
对于您描述的应用程序,您可以使用 ValueAnimator
并在其上设置 AnimatorUpdateListener
以记录每个动画帧之后的状态。
要监听方向变化并保持动画状态,您应该首先在清单的 <activity>
标记中包含 android:configChanges="orientation"
。这将确保您的 activity 不会在方向更改时重新创建,并且不会再次调用 onCreate()
。每当发生方向更改时,都会调用 onConfigurationChanged()
,因此您应该覆盖它以保持动画状态。
因此,在您的 onCreate()
中,您可以执行以下操作:
ValueAnimator valueAnimator = ValueAnimator.ofObject(new IntEvaluator(),
initialPosition, finalPosition);
valueAnimator.setDuration(duration);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
// mCurrentPosition should be a member variable
mCurrentPosition = (int)animation.getAnimatedValue();
// Update the position of your button with currentPosition
}
}
valueAnimator.start();
你的 onConfigurationChanged()
应该是这样的:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.your_layout);
// Set the position of your button with mCurrentPosition
}
更多信息,请参考https://developer.android.com/reference/android/animation/ValueAnimator.html and https://developer.android.com/guide/topics/resources/runtime-changes.html。