如何在Kotlin中为RecyclerView添加项目分隔符

b5lpy0ml  于 2023-06-30  发布在  Kotlin
关注(0)|答案(3)|浏览(167)

我正在开发一个应用程序,我有一个recyclerview列表,我想添加一个项目分隔符。我已经创建了ItemDividerDecorator类和xml布局文件,但我没有连接到回收器视图。
我知道如何在java中做,类似这样的:

recyclerView.addItemDecoration(
                new DividerItemDecoration(ContextCompat.getDrawable(getApplicationContext(),
                        R.drawable.item_separator)));

但是我怎么能在Kotlin中做,我也试图在Android Studio中转换它,但显示了几个错误。这是我的装饰类:

private val mdivider:Drawable
    init{
        this.mdivider = mdivider
    }
    override fun onDrawOver(canvas: Canvas, parent:RecyclerView, state:RecyclerView.State) {
        val left = parent.getPaddingLeft()
        val right = parent.getWidth() - parent.getPaddingRight()
        val childCount = parent.getChildCount()
        for (i in 0 until childCount)
        {
            val child = parent.getChildAt(i)
            val params = child.getLayoutParams() as RecyclerView.LayoutParams
            val top = child.getBottom() + params.bottomMargin
            val bottom = top + mdivider.getIntrinsicHeight()
            mdivider.setBounds(left, top, right, bottom)
            mdivider.draw(canvas)
        }
    }

任何帮助都很感激

dgsult0t

dgsult0t1#

对于Kotlin:

recycler_view.addItemDecoration(
            DividerItemDecoration(
                context,
                LinearLayoutManager.HORIZONTAL
            )
        )

如果你这样初始化:

private lateint var context:Context

然后在onCreateView中

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Intialize context here 
    context = parent.context()
    rootView = container?.inflateView(layoutToInflate) ?: View(context)
    onFragmentCreated(rootView)
    return rootView
}

如果你在一个活动中使用,那么使用
applicationContext

val decorator = DividerItemDecoration(applicationContext, LinearLayoutManager.VERTICAL)
            decorator.setDrawable(ContextCompat.getDrawable(applicationContext, R.drawable.file)!!)
            recycler_view.addItemDecoration(decorator)
ttvkxqim

ttvkxqim2#

Kotlin中尝试此操作
默认项目分隔符

recyclerview.addItemDecoration(DividerItemDecoration(this@YourActivity, LinearLayoutManager.VERTICAL))

可绘制为项目分隔符

val divider = DividerItemDecoration(this@MainActivity,DividerItemDecoration.VERTICAL)
divider.setDrawable(ContextCompat.getDrawable(this@MainActivity,R.drawable.item_separator)!!)
recyclerview.addItemDecoration(divider)

对于Java

recyclerView.addItemDecoration(new DividerItemDecoration(getContext(),LinearLayoutManager.VERTICAL));
fumotvh3

fumotvh33#

添加材质分隔符为

val itemDecorator = MaterialDividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL).apply {
        dividerInsetEnd = 56
        dividerInsetStart = 56
    }

并分配给回收器视图,

sampleRv.addItemDecoration(itemDecorator)

在apply范围内,您可以自定义特定于分隔符的内容,例如插入,颜色等。

相关问题