安卓实现View的滚动效果_android view 组件 滚动_删库且跑路的博客
重点主要在于在每次触摸事件中计算和上次触摸事件的偏移值,然后滚动这个距离
看代码(代码没有考虑很多边缘情况,主要是为了体现滚动的主要实现,对意外情况的考虑需要自行实现):
class HpScrollView(context: Context, attrs: AttributeSet): LinearLayout(context, attrs) {
// 上一次触摸事件的y坐标
private var lastY = 0f
override fun onTouchEvent(event: MotionEvent): Boolean {
if (!super.onTouchEvent(event)) {
val eventY = event.y
when(event.actionMasked) {
MotionEvent.ACTION_DOWN -> lastY = eventY
MotionEvent.ACTION_MOVE -> {
val dy = lastY - eventY
scrollTo(0, (scrollY + dy).toInt())
lastY = eventY
}
else -> {}
}
return true
}
return false
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
布局
<?xml version="1.0" encoding="utf-8"?>
<HpScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="240dp"
android:background="@color/test_blue" />
<View
android:layout_width="match_parent"
android:layout_height="240dp"
android:background="@color/test_cyan" />
<View
android:layout_width="match_parent"
android:layout_height="240dp"
android:background="@color/test_green" />
<View
android:layout_width="match_parent"
android:layout_height="240dp"
android:background="@color/test_orange" />
<View
android:layout_width="match_parent"
android:layout_height="240dp"
android:background="@color/test_red" />
<View
android:layout_width="match_parent"
android:layout_height="240dp"
android:background="@color/test_purple" />
</HpScrollView>