以下做出兩處改動
1.添加每次滾動距離設置
2.實現來回滾動
3.代碼使用kotlin
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.animation.LinearInterpolator
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.RecyclerView
import java.lang.ref.WeakReference
class AutoPollRecyclerView(context: Context, attrs: AttributeSet?) : RecyclerView(context, attrs) {
internal var autoPollTask: AutoPollTask
private var running: Boolean = false //標示是否正在自動輪詢
private var canRun: Boolean = false//標示是否可以自動輪詢,可在不需要的是否置false
//改動1:添加每次滾動距離設置
var distanceOnce = 550
set(value) {
autoPollTask = AutoPollTask(this, value)
}
init {
autoPollTask = AutoPollTask(this, distanceOnce)
}
internal class AutoPollTask//使用弱引用持有外部類引用->防止內存泄漏
(reference: AutoPollRecyclerView, private val distanceOnce: Int) : Runnable {
private val mReference: WeakReference<AutoPollRecyclerView> = WeakReference(reference)
private var isScrollToEnd = false
@RequiresApi(Build.VERSION_CODES.M)
override fun run() {
val recyclerView = mReference.get()
if (recyclerView != null && recyclerView.running && recyclerView.canRun) {
//改動2:實現來回滾動
if (recyclerView.computeHorizontalScrollExtent() + recyclerView.computeHorizontalScrollOffset() >= recyclerView.computeHorizontalScrollRange()) {
isScrollToEnd = true
} else if (recyclerView.computeHorizontalScrollOffset() == 0) {
isScrollToEnd = false
}
recyclerView.smoothScrollBy(if (isScrollToEnd) {
-distanceOnce
} else {
distanceOnce
}, 0, LinearInterpolator())
recyclerView.postDelayed(recyclerView.autoPollTask, TIME_AUTO_POLL)
}
}
}
//開啓:如果正在運行,先停止->再開啓
fun start() {
if (running)
stop()
canRun = true
running = true
postDelayed(autoPollTask, TIME_AUTO_POLL)
}
fun stop() {
running = false
removeCallbacks(autoPollTask)
}
override fun onTouchEvent(e: MotionEvent): Boolean {
when (e.action) {
MotionEvent.ACTION_DOWN -> if (running)
stop()
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_OUTSIDE -> if (canRun)
start()
}
return super.onTouchEvent(e)
}
companion object {
private val TIME_AUTO_POLL: Long = 2000
}
}
感謝
參考文檔:https://blog.csdn.net/merbn/article/details/97146937