赞
踩
以下做出两处改动
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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。