开发者

View Animation in onResume doesn't work after rotation change

开发者 https://www.devze.com 2023-03-12 08:30 出处:网络
I animat开发者_JAVA百科e a view in onResume() based on a certain boolean. mView.startAnimation(mAnimation);

I animat开发者_JAVA百科e a view in onResume() based on a certain boolean.

mView.startAnimation(mAnimation);

The animation always starts when returning to the activity, but it never starts when onResume() is called following a screen orientation change. I know that the above line of code is getting called because I checked it with debugging, so the boolean is not the problem.

What's different about an Activity that's coming back from a rotation that would cause an animation not to work?


My Animation was my own extended Animation that slides a view down by modifying its top margin. To find out the correct distance to slide it, I feed it the height of the view that it's sliding down to reveal. However, views don't have any height until onResume() is done, so I was inadvertently feeding it an offset of zero.

When returning from other activities, the view tree already has the heights left over from before. But after a screen rotation, the Activity is completely destroyed, so the views don't have any dimensions in onResume().

I fixed it by doing the following:

final ViewTreeObserver observer = mObscuredView.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    boolean mDone=false;

    @Override
    public void onGlobalLayout() {
    if (!mDone){
        mAnimation.setTranslation(mObscuredView.getMeasuredHeight());
        mView.startAnimation(mAnimation);
        mDone=true;
    }
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消