S.Bozzoni
S.Bozzoni

Reputation: 1002

How to prevent viewpager2 from turning page when a tab is selected

I have a viewpager2 tied to a tablayout with many different fragments holding textviews, i don't want the user to select another tab if he hasn't completed some of the textviews on each fragment. So when a user select another tab i would show a message asking to complete the current fragment data. I tried to select the old tab when a user select another tab in the "onTabUnselected" method of the TabSelectedListener but without success. Here is the code, please look at the TODO comment where i would like to prevent fragment changing.

viewPager = view.findViewById(R.id.mypager)

TabLayoutMediator(tabLayout, viewPager, true, false,
    TabLayoutMediator.TabConfigurationStrategy { tab: TabLayout.Tab, position: Int ->
        tab.text = titles[position]
    }).attach()

tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
    override fun onTabSelected(tab: TabLayout.Tab?) {

    }

    override fun onTabUnselected(tab: TabLayout.Tab?) {
        val currFragment= fragmentSet[tab!!.position]
        if (!currFragment.validateFields()) {
            //TODO: don't change tab, remain in this tab something like tab.aborselectedtTransition
        }
    }

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

})

Can anybody help me please?

Upvotes: 1

Views: 1116

Answers (1)

S.Bozzoni
S.Bozzoni

Reputation: 1002

I solved on my own, instead of using onTabUnselected it's better to use a listener on onTouch event, this way you can prevent viewpager to change page just returning true from onTouchListener. Please vote me if you like it.

viewPager = view.findViewById(R.id.mypager)

TabLayoutMediator(tabLayout, viewPager, true, false,
    TabLayoutMediator.TabConfigurationStrategy { tab: TabLayout.Tab, position: Int ->
                tab.text = titles[position]
                tab.view.setOnTouchListener { v, event -> onTabLayoutTouch(v,event) }
 }).attach()

private fun onTabLayoutTouch(view:View, event:MotionEvent):Boolean {
    val viewTab = view as TabLayout.TabView
    val tabIndex = viewTab.tab?.position?:-1

    var validationOk = true

    if (event.action == MotionEvent.ACTION_DOWN ) {

        val currFragment = fragmentSet[viewPager.currentItem]

        if (viewPager.currentItem!=tabIndex) {
            val validation = currFragment.validateFields()
            if (!validation.validationResult && event.action==MotionEvent.ACTION_DOWN) {
                showMessage(context, "Compila i dati obbligatori.\n ${validation.message}")
                validationOk = false
            }
        }
    }
    return !validationOk
}

Upvotes: 1

Related Questions