本文介绍通过静态代理模式让SnapHelper
的使用者能方便的监听SnapView的位置Snap Position
一、SnapHelper
二、实现Snap Position的监听
如果要实现类似于PickerView的获取当前SnapView位置或者ViewPager onPageSelected(position)
androidx.viewpager2.widget.ViewPager2
基于RecyclerView重新实现了ViewPager功能。
通过适配器模式ScrollEventAdapter
改造RecyclerView.OnScrollListener
SnapHelper
帮助RecyclerView实现了对齐的功能。
-
int findTargetSnapPosition(RecyclerView.LayoutManager layoutManager, int velocityX, int velocityY)
抛动作开始 -
int[] calculateDistanceToFinalSnap(@NonNull RecyclerView.LayoutManager layoutManager, @NonNull View targetView)
最后对齐需要调整的位置
但SnapHelper
类中没有暴露任何接口用于监听事件,如果要实现接口回调只能继承子类来实现。
OnSnapListener
需要实现的回调接口
interface OnSnapListener {
fun onSnapFromFling(position: Int)
fun onFinalSnap(view: View, position: Int)
}
onSnapFromFling(position)
表示抛动作开始,将要对齐到位置position, 只有在触发抛动作时才会回调。
onFinalSnap(view, position)
表示最后对齐需要调整的位置position
position不一定是SnapView能到达的位置(如一屏能显示3项时,居中对齐后Snap Position最小为1)
SnapHelperProxy
对 SnapHelper关键接口实现静态代理
class SnapHelperProxy(private var snapHelper: SnapHelper) : SnapHelper() {
var onSnapListener: OnSnapListener? = null
private var mRecyclerView: RecyclerView? = null
override fun attachToRecyclerView(recyclerView: RecyclerView?) {
super.attachToRecyclerView(recyclerView)
mRecyclerView = recyclerView
val gravityScrollerField = SnapHelper::class.java.getDeclaredField("mGravityScroller")
gravityScrollerField.isAccessible = true
gravityScrollerField.set(snapHelper, gravityScrollerField.get(this))
val field = SnapHelper::class.java.getDeclaredField("mRecyclerView")
field.isAccessible = true
field.set(snapHelper, recyclerView)
}
override fun calculateDistanceToFinalSnap(
layoutManager: LayoutManager,
targetView: View
): IntArray? {
val result = snapHelper.calculateDistanceToFinalSnap(layoutManager, targetView)
onSnapListener?.onFinalSnap(targetView, layoutManager.getPosition(targetView))
return result
}
override fun findSnapView(layoutManager: LayoutManager?): View? {
return snapHelper.findSnapView(layoutManager)
}
override fun findTargetSnapPosition(
layoutManager: LayoutManager?, velocityX: Int,
velocityY: Int
): Int {
val position = snapHelper.findTargetSnapPosition(layoutManager, velocityX, velocityY)
if (position >= 0) {
onSnapListener?.onSnapFromFling(position)
}
return position
}
fun getSnapPosition(): Int {
return mRecyclerView?.layoutManager?.run {
val view = snapHelper.findSnapView(this) ?: return 0
this.getPosition(view)
} ?: 0
}
}
attachToRecyclerView
入口方法,为了让被代理对象snapHelper能正常工作,通过反射给snapHelper的mGravityScroller和mRecyclerView字段进行赋值。
findTargetSnapPosition
抛动作的开始,回调onSnapListener?.onSnapFromFling(position)
calculateDistanceToFinalSnap
滚动结束,回调onSnapListener?.onFinalSnap(targetView, layoutManager.getPosition(targetView))
getSnapPosition
获取Snap Position,如果RecyclerView还处于滚动状态,获取到位置不是最终的位置。
三、PickerView实现
TestAdapter
实现简单Text实现,宽度设置150
class TestAdapter(val context: Context, val data: MutableList<String>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val textView = TextView(context)
textView.width = 150
textView.height = 200
textView.gravity = Gravity.CENTER_HORIZONTAL
return ViewHolder(textView)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
(holder.itemView as TextView).text = data[position]
}
override fun getItemCount(): Int = data.size
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
}
activity_pickerview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/snapResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
PickerViewActivity
实现水平滚动的PickerView, 支持居中对齐,并回调选中位置。
class PickerViewActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_pickerview)
val adapter = TestAdapter(this, (0..59).map {
"$it"
} as MutableList<String>)
recyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
recyclerView.adapter = adapter
//位置对齐和位置监听
val snapHelperProxy = SnapHelperProxy(LinearSnapHelper())
snapHelperProxy.attachToRecyclerView(recyclerView)
snapHelperProxy.onSnapListener = object : OnSnapListener {
override fun onStartSnap(position: Int) {
snapResult.text = "onStartSnap:" + position
}
override fun onFinalSnap(view: View, position: Int) {
Log.i("TAG", "onFinalSnap:" + position + "," + snapHelperProxy.getSnapPosition())
snapResult.text =
"onFinalSnap:" + position + "," + snapHelperProxy.getSnapPosition()
}
}
}
}
SnapHelperProxy(LinearSnapHelper())
通过对LinearSnapHelper的代理来实现多页对齐和位置监听。
通过对SnapHelper的改造就可以实现了类似PickerView的功能了,而且每个ItemView都可以根据Adapter进行自定义,可以是图片也可以是复杂的View,可以充分使用RecyclerView的扩展功能,如复用、动画、装饰器等
三、总结
熟悉SnapHelper代码实现后需要添加回调逻辑,很直接的办法就是继承类后重写相应的方法,然后实现相应的功能。
LinearSnapHelperExtend
实现LinearSnapHelper
的扩展,代码如下:
class LinearSnapHelperExtend : LinearSnapHelper() {
var onSnapListener: OnSnapListener? = null
override fun calculateDistanceToFinalSnap(
layoutManager: RecyclerView.LayoutManager,
targetView: View
): IntArray? {
val result = super.calculateDistanceToFinalSnap(layoutManager, targetView)
onSnapListener?.onFinalSnap(targetView, layoutManager.getPosition(targetView))
return result
}
override fun findTargetSnapPosition(
layoutManager: RecyclerView.LayoutManager?, velocityX: Int,
velocityY: Int
): Int {
val position = super.findTargetSnapPosition(layoutManager, velocityX, velocityY)
if (position >= 0) {
onSnapListener?.onSnapFromFling(position)
}
return position
}
}
class PickerViewActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_pickerview)
val adapter = TestAdapter(this, (0..59).map {
"$it"
} as MutableList<String>)
recyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
recyclerView.adapter = adapter
//位置对齐和位置监听
val snapHelperProxy = LinearSnapHelperExtend()
snapHelperProxy.attachToRecyclerView(recyclerView)
snapHelperProxy.onSnapListener = object : OnSnapListener {
override fun onSnapFromFling(position: Int) {
snapResult.text = "onStartSnap:" + position
}
override fun onFinalSnap(view: View, position: Int) {
snapResult.text = "onFinalSnap:" + position
}
}
}
}
代码跟适用静态代理实现无实质差别。使用上的差别也不大
- 代理模式
val snapHelperProxy = SnapHelperProxy(LinearSnapHelper())
val snapHelperProxy = LinearSnapHelperExtend()
但是 LinearSnapHelperExtend
的实现是对具体的编程,不具备扩展性。如果需要对PagerSnapHelper
添加Snap Position 监听就要再实现 PagerSnapHelperExtend来支持,会造成类膨胀难以维护。
获得更好的扩展性,对抽象类SnapHelper进行改造
1. 条件
- 无法修改原类的代码
- 不想在每个具体子类进行额外的编码
2. 代理模式
使用代理模式 来对类中每个方法添加额外的逻辑。Java动态代理中 Proxy.newProxyInstance()
只能代理接口类,而SnapHelper是抽象类,无法使用该工具代理对应的方法,引用AOP的动态代理库只会增加项目的复杂度。所以本文采用的是静态代理方式来实现,通过代理SnapHelper关键的方法来实现OnSnapListener
,从而达到对所有SnapHelper的子类也适用。
静态代理也增加了SnapHelperProxy类的维护难度,这里使用反射如果字段名改了就会影响到功能的正常。