For the application you've described, you could use a ValueAnimator
and set an AnimatorUpdateListener
on it to record the state after each animation frame.
To listen for orientation changes and persist the state of the animation, you should first include android:configChanges="orientation"
within the <activity>
tag of your Manifest. This will ensure that your activity is not recreated on orientation change and that onCreate()
won't be called again. Whenever an orientation change occurs, onConfigurationChanged()
will be called, so you should override it to persist the animation state.
So, in your onCreate()
you could do something like:
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();
and your onConfigurationChanged()
should look like:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.your_layout);
// Set the position of your button with mCurrentPosition
}
For more info, please refer to https://developer.android.com/reference/android/animation/ValueAnimator.html and https://developer.android.com/guide/topics/resources/runtime-changes.html.