Skip to content

Instantly share code, notes, and snippets.

@Haoxiqiang
Last active September 11, 2023 07:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Haoxiqiang/ac93f1b819d3b8308f81518de972c1de to your computer and use it in GitHub Desktop.
Save Haoxiqiang/ac93f1b819d3b8308f81518de972c1de to your computer and use it in GitHub Desktop.
a more elegant and non-invasive solution for viewpager in bottomsheet.
import android.view.View
import android.view.ViewGroup
import androidx.core.view.ViewCompat
import androidx.viewpager.widget.ViewPager
import androidx.viewpager.widget.ViewPagerUtils
import com.google.android.material.bottomsheet.BottomSheetBehavior
import java.lang.ref.WeakReference
import java.lang.reflect.Field
private val nestedScrollingChildRef: Field =
BottomSheetBehavior::class.java.getDeclaredField("nestedScrollingChildRef")
fun BottomSheetBehavior<out ViewGroup>.resetScrollingChild(view: View) {
// @Nullable WeakReference<View> nestedScrollingChildRef;
val v = findScrollingChild(view)
nestedScrollingChildRef.isAccessible = true
nestedScrollingChildRef.set(this, WeakReference(v))
}
private fun findScrollingChild(view: View?): View? {
if (view == null || view.visibility != View.VISIBLE) {
return null
}
if (view is ViewPager) {
//通过ViewPagerUtils找到当前在界面上的页面
val currentViewPagerChild = ViewPagerUtils.getCurrentView(view)
val scrollingChild = findScrollingChild(currentViewPagerChild)
return scrollingChild ?: currentViewPagerChild
} else if (ViewCompat.isNestedScrollingEnabled(view)) {
return view
} else if (view is ViewGroup) {
var i = 0
val count = view.childCount
while (i < count) {
val scrollingChild = findScrollingChild(view.getChildAt(i))
if (scrollingChild != null) {
return scrollingChild
}
i++
}
}
return null
}
viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
}
override fun onPageSelected(position: Int) {
behavior.resetScrollingChild(viewPager)
}
override fun onPageScrollStateChanged(state: Int) {
}
})
package androidx.viewpager.widget;
import android.view.View;
public class ViewPagerUtils {
public static View getCurrentView(ViewPager viewPager) {
final int currentItem = viewPager.getCurrentItem();
for (int i = 0; i < viewPager.getChildCount(); i++) {
final View child = viewPager.getChildAt(i);
final ViewPager.LayoutParams layoutParams = (ViewPager.LayoutParams) child.getLayoutParams();
if (!layoutParams.isDecor && currentItem == layoutParams.position) {
return child;
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment