How to disable “Window animation scale” programmat

2019-04-07 11:08发布

问题:

I'm using a Service that displays a view using WindowManager, and animation occurs every time I change the view's size using

windowManagerLayoutParams.height = newHeight;
((WindowManager) getSystemService(WINDOW_SERVICE)).updateViewLayout(mMainLayout, windowManagerLayoutParams);

If I disable manually the scale animations, no animation occurs. Scale animation disabled manually like so: http://www.cultofandroid.com/11143/android-4-0-tip-how-to-find-and-disable-animations-for-a-snappier-experience/

Is there a way to disable the window scale animations for my application programmatically?

回答1:

I just had this same problem while working on a system overlay in the SystemUI package and decided to dig through the source to see if I could find a solution. WindowManager.LayoutParams has some hidden goodies that can solve this problem. The trick is to use the privateFlags member of WindowManager.LayoutParams like so:

windowManagerLayoutParams.privateFlags |= 0x00000040;

If you look at line 1019 of WindowManager.java you'll see that 0x00000040 is the value for PRIVATE_FLAG_NO_MOVE_ANIMATION. For me this did stop window animations from occurring on my view when I change the size via updateViewLayout()

I had the advantage of working on a system package so I am able to access privateFlags directly in my code but you are going to need to use reflection if you want to access this field.



回答2:

As @clark stated this can be changed using reflection:

private void disableAnimations() {
    try {
        int currentFlags = (Integer) mLayoutParams.getClass().getField("privateFlags").get(mLayoutParams);
        mLayoutParams.getClass().getField("privateFlags").set(mLayoutParams, currentFlags|0x00000040);
    } catch (Exception e) {
        //do nothing. Probably using other version of android
    }
}


回答3:

Did you try Activity#overridePendingTransition(0, 0)?

Check out the documentation:

Call immediately after one of the flavors of startActivity(Intent) or finish() to specify an explicit transition animation to perform next.