-
-
Notifications
You must be signed in to change notification settings - Fork 148
ViewPager1和ViewPager2
angcyo edited this page Dec 3, 2020
·
3 revisions
1.4.2
之后, 可以使用:
implementation 'com.github.angcyo.DslTablayout:ViewPager1Delegate:1.4.2'
implementation 'com.github.angcyo.DslTablayout:ViewPager2Delegate:1.4.2'
ViewPager1Delegate.install(viewPager, dslTabLayout)
ViewPager2Delegate.install(viewPager2, dslTabLayout)
进行关联操作.
旧文如下:
为了兼容"androidx.viewpager:viewpager"
和 "androidx.viewpager2:viewpager2"
而又不想在库中强引入这2个库.
所以需要开发者自行转发onPageScrolled
事件给DslTabLayout
.
原来的方法setupViewPager(viewPager: ViewPager)
, 改成了setupViewPager(viewPagerDelegate: ViewPagerDelegate)
请使用以下的类:
/**
* 兼容[ViewPager]
* Email:angcyo@126.com
* @author angcyo
* @date 2019/12/14
*/
class ViewPager1Delegate(val viewPager: ViewPager, val dslTabLayout: DslTabLayout) :
ViewPager.OnPageChangeListener, ViewPagerDelegate {
init {
viewPager.addOnPageChangeListener(this)
}
override fun onGetCurrentItem(): Int {
return viewPager.currentItem
}
override fun onSetCurrentItem(fromIndex: Int, toIndex: Int) {
viewPager.setCurrentItem(toIndex, (toIndex - fromIndex).absoluteValue <= 1)
}
override fun onPageScrollStateChanged(state: Int) {
dslTabLayout.onPageScrollStateChanged(state)
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
dslTabLayout.onPageScrolled(position, positionOffset, positionOffsetPixels)
}
override fun onPageSelected(position: Int) {
dslTabLayout.onPageSelected(position)
}
}
请使用以下的类:
/**
* 兼容[ViewPager2]
* Email:angcyo@126.com
* @author angcyo
* @date 2019/12/14
*/
class ViewPager2Delegate(val viewPager: ViewPager2, val dslTabLayout: DslTabLayout) :
ViewPager2.OnPageChangeCallback(), ViewPagerDelegate {
init {
viewPager.registerOnPageChangeCallback(this)
}
override fun onGetCurrentItem(): Int {
return viewPager.currentItem
}
override fun onSetCurrentItem(fromIndex: Int, toIndex: Int) {
viewPager.setCurrentItem(toIndex, (toIndex - fromIndex).absoluteValue <= 1)
}
override fun onPageScrollStateChanged(state: Int) {
dslTabLayout.onPageScrollStateChanged(state)
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
dslTabLayout.onPageScrolled(position, positionOffset, positionOffsetPixels)
}
override fun onPageSelected(position: Int) {
dslTabLayout.onPageSelected(position)
}
}
本来想把这2个类打成
library
, 考虑到依赖库的版本冲突的原因, 先搁置以下.
注意
如果覆盖了onSelectIndexChange
操作, 那么ViewPager
和ViewPager2
的操作需要手动触发.
触发代码dslTablayout._viewPagerDelegate?.onSetCurrentItem(fromIndex, toIndex)
//如果设置[tabLayoutConfig?.onSelectIndexChange], 那么会覆盖[_viewPagerDelegate]的操作.
tabLayoutConfig?.onSelectIndexChange?.invoke(
fromIndex,
selectList,
reselect,
fromUser
) ?: _viewPagerDelegate?.onSetCurrentItem(fromIndex, toIndex)