Android RecyclerView は、LinearSnapHelper を使用して ViewPager 効果を実現します

転載元を示してください: http://blog.csdn.net/zhaoyanjun6/article/details/128801968この記事は[Zhao Yanjun のブログ]
からのものです。

記事ディレクトリ

LinearSnapHelper エフェクト

すべてのコードは github にアップロードされます

https://github.com/zyj1609wz/SnapHelperApp

SnapHelper は RecyclerView の機能を拡張したもので、RecyclerView のスライド動作を ViewPager と似たものにします。どのようにスライドしても、最終的に特定のページの途中にとどまります。ViewPager は一度に 1 ページしかスライドできず、RecyclerView+SnapHelper メソッドは一度に複数のページをスライドでき、最終的に特定のページの途中にとどまります。非常に実用的でクールです。

SnapHelper の実装原理は、RecyclerView.OnFlingListener で onFling インターフェイスを監視することです。LinearSnapHelper は、抽象クラス SnapHelper の具体的な実装です

ここに画像の説明を挿入

上記の効果には、次のコード行のみが必要です

val snapHelper = LinearSnapHelper()
//保证recyclerView滚动停止是,可以停在中间位置,类似于viewPager效果
       snapHelper.attachToRecyclerView(binding.recycler)

次のように、全体的なコードは非常に小さいです。

class MainActivity : AppCompatActivity() {
    
    

    private lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
        binding.recycler.layoutManager = layoutManager
        binding.recycler.adapter = MyAdapter(listOf("1", "2", "3", "4", "5", "6", "7", "8"))

        val snapHelper = LinearSnapHelper()
        //保证recyclerView滚动停止是,可以停在中间位置,类似于viewPager效果
        snapHelper.attachToRecyclerView(binding.recycler)

        binding.btn.setOnClickListener {
    
    
            //获取中间位置的position
            val view = snapHelper.findSnapView(layoutManager)
            if (view != null) {
    
    
                val position = layoutManager.getPosition(view)
                Toast.makeText(this, " $position", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

おすすめ

転載: blog.csdn.net/zhaoyanjun6/article/details/128801968