Can I change the Android startActivity() transition animation?

后端 未结 10 1674
臣服心动
臣服心动 2020-11-28 19:53

I am starting an activity and would rather have a alpha fade-in for startActivity(), and a fade-out for the finish(). How can I go about this in th

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 20:09

    I wanted to use the styles.xml solution, but it did not work for me with activities. Turns out that instead of using android:windowEnterAnimation and android:windowExitAnimation, I need to use the activity animations like this:

    
    

    Also, for some reason this only worked from Android 8 and above. I added the following code to my BaseActivity, to fix it for the API levels below:

    override fun finish() {
        super.finish()
        setAnimationsFix()
    }
    
    /**
     * The activityCloseExitAnimation and activityCloseEnterAnimation properties do not work correctly when applied from the theme.
     * So in this fix, we retrieve them from the theme, and apply them.
     * @suppress Incorrect warning: https://stackoverflow.com/a/36263900/1395437
     */
    @SuppressLint("ResourceType")
    private fun setAnimationsFix() {
        // Retrieve the animations set in the theme applied to this activity in the manifest..
        var activityStyle = theme.obtainStyledAttributes(intArrayOf(attr.windowAnimationStyle))
        val windowAnimationStyleResId = activityStyle.getResourceId(0, 0)
        activityStyle.recycle()
        // Now retrieve the resource ids of the actual animations used in the animation style pointed to by
        // the window animation resource id.
        activityStyle = theme.obtainStyledAttributes(windowAnimationStyleResId, intArrayOf(activityCloseEnterAnimation, activityCloseExitAnimation))
        val activityCloseEnterAnimation = activityStyle.getResourceId(0, 0)
        val activityCloseExitAnimation = activityStyle.getResourceId(1, 0)
        activityStyle.recycle()
        overridePendingTransition(activityCloseEnterAnimation, activityCloseExitAnimation);
    }
    

提交回复
热议问题