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

2024-01-02

我正在开发一个应用程序,其中有一个带有 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)
        }
    }

任何帮助表示赞赏


对于科特林:

 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
}

如果您在活动内部使用,则改为使用

应用上下文

val decorator = DividerItemDecoration(applicationContext, LinearLayoutManager.VERTICAL)
            decorator.setDrawable(ContextCompat.getDrawable(applicationContext, R.drawable.file)!!)
            recycler_view.addItemDecoration(decorator)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Kotlin 中为 RecyclerView 添加项目分隔线 的相关文章

随机推荐