使用MotionLayout 实现启动页动画 Splash

使用MotionLayout 实现启动页动画 Splash

效果图

capture.gif

项目地址

具体代码实现

activity_splash.xml



    
    


    


xml/activity_motion_scene/xml




    
        
        
            
            
            
            
            

        
    

    

        

        

    

    
        
        

    


SplashActivity

package com.e9ab98e991ab.motionsplash

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.motion.widget.MotionLayout
import kotlinx.android.synthetic.main.activity_splash.*

class SplashActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        }
        main_image2.post {
            main_image2.performClick()
        }
        _splashMotion.setTransitionListener(object : MotionLayout.TransitionListener {
            override fun onTransitionStarted(p0: MotionLayout?, p1: Int, p2: Int) {
            }

            override fun onTransitionChange(p0: MotionLayout?, p1: Int, p2: Int, p3: Float) {
            }

            override fun onTransitionCompleted(p0: MotionLayout?, p1: Int) {
                startActivity(Intent(this@SplashActivity, MainActivity::class.java))
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
                [email protected]()
            }

            override fun onTransitionTrigger(p0: MotionLayout?, p1: Int, p2: Boolean, p3: Float) {
            }
        })
    }
}

实现原理

第一步:SplashActivity 中使用MotionLayout (id: _splashMotion)添加 ImageView (id: main_image2)

第二步:MotionScene->Transition添加 如下事件监听 并在MotionScene 布局中调整动画角度。


第三步 SplashActivity 中 执行 performClick()开始执行动画

main_image2.post {
    main_image2.performClick()
}

第四步 在SplashActivity(id: _splashMotion) 设置动画监听

_splashMotion.setTransitionListener(object : MotionLayout.TransitionListener {
    //开始时
    override fun onTransitionStarted(p0: MotionLayout?, p1: Int, p2: Int) {
    }

    override fun onTransitionChange(p0: MotionLayout?, p1: Int, p2: Int, p3: Float) {
    }
    //结束
    override fun onTransitionCompleted(p0: MotionLayout?, p1: Int) {
        startActivity(Intent(this@SplashActivity, MainActivity::class.java))
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
        [email protected]()
    }

    override fun onTransitionTrigger(p0: MotionLayout?, p1: Int, p2: Boolean, p3: Float) {
    }
})

你可能感兴趣的:(使用MotionLayout 实现启动页动画 Splash)