Android RecycleView滑動停止后自動吸附效果的實現(xiàn)代碼(滑動定位)
最近有個需求 要求列表 滑動后第一條 需要和頂部對齊上網(wǎng)找了找 發(fā)現(xiàn) 官方支持 Recycle + LinearSnapHelper 可以實現(xiàn)但我實際操作加上后 發(fā)現(xiàn)會卡頓 滑動卡頓 沒有以前那種流暢感了
想了想 算了 懶得看源碼 還是自己寫一個得了
效果圖 :
代碼如下 注釋很清楚了
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 表示是否是 第二次定位滑動 @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以內(nèi) 其實時接近停止了 慢速滑動了 這時我們讓他停止 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 毫秒延時任務(wù) }}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)//二次滑動 } } }}
結(jié)束
到此這篇關(guān)于Android RecycleView滑動停止后自動吸附效果的實現(xiàn)代碼(滑動定位)的文章就介紹到這了,更多相關(guān)Android RecycleView滑動定位內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. php使用正則驗證密碼字段的復(fù)雜強度原理詳細講解 原創(chuàng)2. 基于javaweb+jsp實現(xiàn)企業(yè)車輛管理系統(tǒng)3. HTML5實戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)4. ASP將數(shù)字轉(zhuǎn)中文數(shù)字(大寫金額)的函數(shù)5. Jsp servlet驗證碼工具類分享6. jscript與vbscript 操作XML元素屬性的代碼7. 基于PHP做個圖片防盜鏈8. Jsp+Servlet實現(xiàn)文件上傳下載 文件列表展示(二)9. asp.net core 認證和授權(quán)實例詳解10. XML在語音合成中的應(yīng)用
