'Smooth animation when tab switches

I am using ActionBar.Tabs with ViewPager, and it looks like enter image description here

I implemented the ActionBar.TabListener and ViewPager.OnPageChangeListener to support that when user swipe pages in ViewPager, the tab indicator will change accordingly (the blue indicator will move to the corresponding tab).

Now I realized that the blue indicator changes without any animation, and it doesn't look good. (when I swipe from tab1 to tab2, the blue indicator disappear under tab1 and appear under tab2). Is there a way to change it so that when I switch tabs, the blue tab indicator moves smoothly between tabs?



Solution 1:[1]

Use the TabLayout class from the design support library: https://developer.android.com/reference/android/support/design/widget/TabLayout.html

It has a setupWithViewPager to easily connect it with a ViewPager, and it has a sliding indicator bar.

Solution 2:[2]

In my case it appeared because of TabSelectedListener. In tab_layout.addOnTabSelectedListener() I overrode a onTabSelected method, where I opened another activity without a delay.

view.tab_layout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
    override fun onTabReselected(tab: TabLayout.Tab?) {
    }

    override fun onTabUnselected(tab: TabLayout.Tab?) {
    }

    override fun onTabSelected(tab: TabLayout.Tab?) {
        if (tab?.position == 1) {
            MapsActivity.showScreen(this@ThisFragment)
        }
    }
})

I rewrote that method with a delay:

    override fun onTabSelected(tab: TabLayout.Tab?) {
        if (tab?.position == 1) {
            // Show tab animation and open an activity.
            view.tab_layout.postDelayed({
                // This check is optional.
                if (isAdded && view.tab_layout.selectedTabPosition == 1) {
                    MapsActivity.showScreen(this@YourFragment)
                }
            }, 250)
        }
    }

Also I tried to change a duration value, but don't know how (didn't help):

view.tab_layout.animation = object: Animation() {}
view.tab_layout.animation.duration = 1000
view.tab_layout.layoutAnimation = LayoutAnimationController(object: Animation() {})
view.tab_layout.layoutAnimation.delay = 1000f
view.tab_layout.layoutAnimation.animation.duration = 1000

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 marmor
Solution 2