Change title animation on ViewPager2 scroll/selection

36 Views Asked by At

I have layout consisting of TextView and ViewPager2. When I change page OR scroll to new page, I would like to change content of the TextView with animation. My code:

binding.viewpager.adapter = MyAdapter(this)
TabLayoutMediator(binding.intoTabLayout, binding.viewpager) { _, _ -> }.attach()
binding.viewpager.registerOnPageChangeCallback(object: OnPageChangeCallback() {
    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
        super.onPageScrolled(position, positionOffset, positionOffsetPixels)
    }

    override fun onPageSelected(position: Int) {
        when (position) {
            0 -> binding.myTextView.text = "First page"
            1 -> binding.myTextView.text = "Second page"
        }
        super.onPageSelected(position)
    }
})

Changing text content is not a problem - in onPageSelected, I can detect the position. However, problem is with an animation. Let's say I want to use fade out/fade in animation:

// Fade out
val fadeOut = AlphaAnimation(1.0f, 0.0f)
binding.myTextView.startAnimation(fadeOut)

// Fade in
val fadeIn = AlphaAnimation(0.0f, 1.0f)
binding.myTextView.startAnimation(fadeIn)

Where to put this? How to achieve such event? I tried to put it inside onPageScrolled:

override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
    if (positionOffsetPixels != 0) {
        val fadeOut = AlphaAnimation(1.0f, 0.0f)
        binding.myTextView.startAnimation(fadeOut)
    }
    super.onPageScrolled(position, positionOffset, positionOffsetPixels)
}

but it does not work correctly - in case user swipes, it is OK, however, when user clicks on dot indicator item below, title changes and then the text fades out. Can somebody advise, how to do this correctly? I want to avoid simply changing the items, I would like to have some nice and smooth animation there. Thank you.

0

There are 0 best solutions below