Syed Kabeer
Syed Kabeer

Reputation: 67

How to handle TabLayout click before taking user to the next tab?

I have four tabs with ViewPager attached to the OnTabSelected. One of the tab contains Form fields, once user make any change I shouldn't let the user move to next tab unless he saves the changes.

(In other words should throw alert on OnTabSelected instead of taking the user to next tab)

But I cannot control the TabLayout -> "addOnTabSelectedListener"

Any help would be great

binding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
    override fun onTabSelected(tab: TabLayout.Tab) {
        if (State.isClear()) {
            showNextTab()
        } else {
            showSaveSelectionAlert()
        }
    }

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

    override fun onTabReselected(tab: TabLayout.Tab) {
    }
})

Upvotes: 2

Views: 718

Answers (2)

Akash Patel
Akash Patel

Reputation: 3141

boolean isShowNext = true;

if(isShowNext)
{
   viewPager.setCurrentItem(1);
}
else{
   // show alert here
}

Upvotes: 0

Rene Ferrari
Rene Ferrari

Reputation: 4206

Refer to this answer. The CustomViewPager shown there is not allowing any scrolling what so ever unless you specifically allow it by setting setPagingEnabled to true. What my idea would be to have setPagingEnabled to false until the user has filled out all the fields. If this is the case, paging will be enabled again and therefore the user can swipe to the next tab. Otherwise error messages will appear.

We can extend this further and make it applicable to the TabLayout as well. This answer shows you how to disable click of a Tab. The onTouch has to be overriden a bit differently though. If all your criteria are met, you should return false - meaning the user can switch the tab. Else display error messages.

So in short: Disable paging of ViewPager and tab switching of TabLayout with help of the links I have provided you. Enable it once your criteria are met, else show errors.

Upvotes: 1

Related Questions