这篇文章将为大家详细讲解有关Android RecycleView实现滑动停止后自动吸附效果,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
package com.example.testapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.testapp.code.note.JoinData
import com.example.testapp.code.note.TheatreJoinerAdapter
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
//isUserControl 表示是否是 第二次定位滑动
@Volatile
private var isUserControl = false
var runnable = Runnable {
smoothScrollToPosition()//处理rcy定位
}
val list = arrayListOf<JoinData>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
for (i in 0..50) {
list.add(JoinData("小名${i}", i))
}
rcy.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
var adapter = TheatreJoinerAdapter(this, list)
rcy.adapter = adapter
rcy.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(r: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(r, dx, dy)
//判断是否是自动滚动
if (r.scrollState == RecyclerView.SCROLL_STATE_SETTLING && !isUserControl) {//自动滚动
//滚动幅度 在 -3 .. 3以内 其实时接近停止了 慢速滑动了 这时我们让他停止
if (dy in -3..3) {//向下滚动
r.stopScroll()
}
}
}
override fun onScrollStateChanged(r: RecyclerView, newState: Int) {
super.onScrollStateChanged(r, newState)
if (newState == RecyclerView.SCROLL_STATE_IDLE) {//滑动停止
if (!isUserControl) {
rcy.postDelayed(runnable, 200)//200 毫秒延时任务
}
}
if (r.scrollState != RecyclerView.SCROLL_STATE_SETTLING) {//非自动滑动
isUserControl = false
}
}
})
}
private fun smoothScrollToPosition() {
isUserControl = true
val stickyInfoView = rcy.getChildAt(0) //获取头部View 第一个view
val bottom = stickyInfoView.bottom//获取view底部到rcy的顶部高度
val height = stickyInfoView.measuredHeight//获取view高度
if (bottom != height) {//去除正好停在正好的位置的情况
if (bottom >= (height / 2)) {//判断view在上一半还是在下一半
rcy.smoothScrollBy(0, -(height - bottom))//二次滑动
} else {
rcy.smoothScrollBy(0, bottom)//二次滑动
}
}
}
}
关于Android RecycleView实现滑动停止后自动吸附效果就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。