Android RecycleView滑動(dòng)停止后自動(dòng)吸附效果的實(shí)現(xiàn)代碼(滑動(dòng)定位)
最近有個(gè)需求 要求列表 滑動(dòng)后第一條 需要和頂部對(duì)齊上網(wǎng)找了找 發(fā)現(xiàn) 官方支持 Recycle + LinearSnapHelper 可以實(shí)現(xiàn)但我實(shí)際操作加上后 發(fā)現(xiàn)會(huì)卡頓 滑動(dòng)卡頓 沒(méi)有以前那種流暢感了
想了想 算了 懶得看源碼 還是自己寫(xiě)一個(gè)得了
效果圖 :
代碼如下 注釋很清楚了
package com.example.testapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport androidx.recyclerview.widget.LinearLayoutManagerimport androidx.recyclerview.widget.RecyclerViewimport com.example.testapp.code.note.JoinDataimport com.example.testapp.code.note.TheatreJoinerAdapterimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { //isUserControl 表示是否是 第二次定位滑動(dòng) @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)//判斷是否是自動(dòng)滾動(dòng)if (r.scrollState == RecyclerView.SCROLL_STATE_SETTLING && !isUserControl) {//自動(dòng)滾動(dòng) //滾動(dòng)幅度 在 -3 .. 3以內(nèi) 其實(shí)時(shí)接近停止了 慢速滑動(dòng)了 這時(shí)我們讓他停止 if (dy in -3..3) {//向下滾動(dòng) r.stopScroll() }} } override fun onScrollStateChanged(r: RecyclerView, newState: Int) {super.onScrollStateChanged(r, newState)if (newState == RecyclerView.SCROLL_STATE_IDLE) {//滑動(dòng)停止 if (!isUserControl) { rcy.postDelayed(runnable, 200)//200 毫秒延時(shí)任務(wù) }}if (r.scrollState != RecyclerView.SCROLL_STATE_SETTLING) {//非自動(dòng)滑動(dòng) isUserControl = false} } }) } private fun smoothScrollToPosition() { isUserControl = true val stickyInfoView = rcy.getChildAt(0) //獲取頭部View 第一個(gè)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))//二次滑動(dòng) } else {rcy.smoothScrollBy(0, bottom)//二次滑動(dòng) } } }}
結(jié)束
到此這篇關(guān)于Android RecycleView滑動(dòng)停止后自動(dòng)吸附效果的實(shí)現(xiàn)代碼(滑動(dòng)定位)的文章就介紹到這了,更多相關(guān)Android RecycleView滑動(dòng)定位內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. python爬蟲(chóng)實(shí)戰(zhàn)之制作屬于自己的一個(gè)IP代理模塊2. asp批量添加修改刪除操作示例代碼3. 基于javaweb+jsp實(shí)現(xiàn)企業(yè)財(cái)務(wù)記賬管理系統(tǒng)4. css代碼優(yōu)化的12個(gè)技巧5. 如何在jsp界面中插入圖片6. 解決ajax請(qǐng)求后臺(tái),有時(shí)收不到返回值的問(wèn)題7. PHP獲取時(shí)間戳等相關(guān)函數(shù)匯總8. Ajax返回值類型與用法實(shí)例分析9. .NET6打包部署到Windows Service的全過(guò)程10. HTML 絕對(duì)路徑與相對(duì)路徑概念詳細(xì)
