gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:58:36 25 4
gpt4 key购买 nike

我正在开发一个应用程序,其中有一个带有 recyclerview 的列表,我想为项目添加一个分隔符。我已经创建了 ItemDividerDecorator 类和 xml 布局文件,但我没有连接到回收器 View 。

我知道如何在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)
}
}

任何帮助表示赞赏

最佳答案

对于 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
}

如果您在 Activity 中使用,则改为使用

applicationContext


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

关于android - 如何在 Kotlin 中为 RecyclerView 添加项目分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57886100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com