Android ViewPager with RecyclerView works incorrectly inside BottomSheet

后端 未结 7 1018
故里飘歌
故里飘歌 2020-12-13 02:51

When I try to scroll list, sometimes this works incorrect - BottomSheet intercepts the scroll event and hides.

How to reproduce this:

  1. Open Bottom Sheet
7条回答
  •  离开以前
    2020-12-13 03:22

    I have the solution for AndroidX, Kotlin. Tested and working on 'com.google.android.material:material:1.1.0-alpha06'.

    I also used this: MEDIUM BLOG as a guide.

    Here is My ViewPagerBottomSheetBehavior Kotlin Class:

    package com.google.android.material.bottomsheet
    import android.content.Context
    import android.util.AttributeSet
    import android.view.View
    import androidx.annotation.VisibleForTesting
    import androidx.viewpager.widget.ViewPager
    import java.lang.ref.WeakReference
    class ViewPagerBottomSheetBehavior
        : com.google.android.material.bottomsheet.BottomSheetBehavior,
        ViewPager.OnPageChangeListener {
    
        constructor() : super()
        constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    
        override fun onPageScrollStateChanged(state: Int) {}
        override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
        override fun onPageSelected(position: Int) {
            val container = viewRef?.get() ?: return
            nestedScrollingChildRef = WeakReference(findScrollingChild(container))
        }
    
        @VisibleForTesting
        override fun findScrollingChild(view: View?): View? {
            return if (view is ViewPager) {
                view.focusedChild?.let { findScrollingChild(it) }
            } else {
                super.findScrollingChild(view)
            }
        }
    }
    

    The final solutios was adding the super constructors in the Class:

    constructor() : super()
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    

    Remember, you have to add ViewPagerBottomSheetBehavior Kotlin Class in the next path: Path Class Image reference because, you must override a private method>

    @VisibleForTesting
    override fun findScrollingChild(view: View?): View? {
        return if (view is ViewPager) {
            view.focusedChild?.let { findScrollingChild(it) }
        } else {
            super.findScrollingChild(view)
        }
    }
    

    After that, you can use it as a View attribute, like this>

            
            
        
    

提交回复
热议问题