NSouth
NSouth

Reputation: 5276

How do I disable swiping on FragmentStatePagerAdapter?

I'm following the tutorial here which uses a TabLayout with a FragmentStatePagerAdapter. Everything is great, except I need to disable swiping on my second tab, as it uses horizontal scrolling. It's okay if scrolling is disabled for all tabs, but It would be awesome if it were only disabled for the second one.

It looks like for a ViewPager I would override the onInterceptTouchEvent() method, but this does not appear to be an option for FragmentStatePagerAdapter. Any ideas on how to do this? Thanks.

Edit: I only have two fragments, so if FragmentStatePagerAdapter is not appropriate, I'm open to suggestions.

Edit 2: the problem of not swiping has been solved. However, I'd still like to know how to prevent swiping for only the 2nd fragment.

Upvotes: 2

Views: 5149

Answers (2)

Droid Chris
Droid Chris

Reputation: 3783

OK this is how this is done:

Here is my FragmentStateAdapter -

class ViewPagerAdapter(
    fragmentManager: FragmentManager,
    private val totalTabs: Int,
    lifecycle: Lifecycle,
) : FragmentStateAdapter(fragmentManager, lifecycle) {

    override fun getItemCount(): Int = totalTabs

    override fun createFragment(position: Int): Fragment {
        return when (position) {
            0 -> RadioFragment()
            1 -> ThingsToDoInTheAreaMapFragment()
            2 -> SavedRadioStationsFragment()
            else -> RadioFragment()
        }
    }

}

Here is the XML:

<androidx.viewpager2.widget.ViewPager2
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:visibility="gone"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintBottom_toTopOf="@+id/app_bar_layout" />

Here is my implementation of it:

binding.viewPager.adapter = ViewPagerAdapter(
                supportFragmentManager,
                binding.tabsLayout.tabCount,
                lifecycle
            )

Then to disable swiping, add the following line after creating the adapter:

binding.viewPager.isUserInputEnabled = false

Upvotes: 0

tachyonflux
tachyonflux

Reputation: 20221

Modify the onInterceptTouchEvent and onTouchEvent to exclude only the tab index that you want:

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    switch(getCurrentItem()){
        case 1:
            return false;
        default:
            return super.onInterceptTouchEvent(event);
    }
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    switch(getCurrentItem()){
        case 1:
            return false;
        default:
            return super.onTouchEvent(event);
    }
}

Upvotes: 0

Related Questions