如何在水平回收站视图中居中选定的项目?

时间:2019-01-18 16:07:41

标签: java android kotlin

我有一个带有arrayList的recylerview,其中包含一周中的全天。当我点击选择日期时,将显示recyclerview。然后,已选择一周中的第三天(默认)。我需要将其居中到recyclerview中,然后,当我在回收商中选择另一天时,它需要再次将所选项目重新居中。 那是我的代码:

        val recyclerViewGiorni = view.giorniRV
        val horizontalLayoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        recyclerViewGiorni.layoutManager = horizontalLayoutManager
        adapter = ButtonPromemoriaAdapter(giorniPromemoria)
        recyclerViewGiorni.adapter = adapter
        val snapHelper = LinearSnapHelper()
        snapHelper.attachToRecyclerView(recyclerViewGiorni)
        recyclerViewGiorni.addOnScrollListener(object : RecyclerView.OnScrollListener() {

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    val centerView = snapHelper.findSnapView(horizontalLayoutManager)
                    val pos = horizontalLayoutManager.getPosition(centerView!!)
                    Log.e("Snapped Item Position:", "" + pos)
                }
            }
        })

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找SpanHelper

SnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(yourRecyclerView);

请看

了解更多信息。