ViewPager2中Fragemnt之间的滑动动画

isUserInputEnabled: 是否允许用户滑动切换item
orientation:控制方向(水平、竖直)
setCurrentItem:切换item(Int参数控制位置,Boolean参数控制是否平滑滚动)
Adapter: FragmentStateAdapter

参考:https://developer.android.com/training/animation/screen-slide-2

    private const val MIN_SCALE = 0.75f

    class DepthPageTransformer : ViewPager2.PageTransformer {
    // 从页面1左滑到页面2 页面1的position:0->-1,页面2的position:1->0
        override fun transformPage(view: View, position: Float) {
            view.apply {
                val pageWidth = width
                when {
                    position < -1 -> { // [-Infinity,-1)
                        // This page is way off-screen to the left.
                        alpha = 0f
                    }
                    position <= 0 -> { // [-1,0]  
                        // Use the default slide transition when moving to the left page
                        alpha = 1f
                        translationX = 0f
                        scaleX = 1f
                        scaleY = 1f
                    }
                    position <= 1 -> { // (0,1]
                        // Fade the page out.
                        alpha = 1 - position

                        // Counteract the default slide transition
                        translationX = pageWidth * -position

                        // Scale the page down (between MIN_SCALE and 1)
                        val scaleFactor = (MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.abs(position)))
                        scaleX = scaleFactor
                        scaleY = scaleFactor
                    }
                    else -> { // (1,+Infinity]
                        // This page is way off-screen to the right.
                        alpha = 0f
                    }
                }
            }
        }
    }
    
    private val translateX get() = viewPager.orientation == ORIENTATION_VERTICAL &&
            translateCheckBox.isChecked
    private val translateY get() = viewPager.orientation == ORIENTATION_HORIZONTAL &&
            translateCheckBox.isChecked

    private val mAnimator = ViewPager2.PageTransformer { page, position ->
        val absPos = Math.abs(position)
        page.apply {
            rotation = if (rotateCheckBox.isChecked) position * 360 else 0f
            translationY = if (translateY) absPos * 500f else 0f
            translationX = if (translateX) absPos * 350f else 0f
            if (scaleCheckBox.isChecked) {
                val scale = if (absPos > 1) 0F else 1 - absPos
                scaleX = scale
                scaleY = scale
            } else {
                scaleX = 1f
                scaleY = 1f
            }
        }
    }

你可能感兴趣的:(ViewPager2中Fragemnt之间的滑动动画)