如何在Kotlin中为RecyclerView添加项目分隔线 [英] How to add item divider for RecyclerView in Kotlin
问题描述
我正在开发一个应用程序,其中有一个带有recyclerview的列表,我想为项目添加一个分隔线.我已经创建了ItemDividerDecorator类和xml布局文件,但是我没有连接到回收站视图.
I'm working on an app where I have a list with recyclerview and I want to add a divider for items. I have created the ItemDividerDecorator class and xml layout file but I'm not connecting to recycler view.
我知道如何用Java来做,就像这样:
I know how to do in java, something like this:
recyclerView.addItemDecoration(
new DividerItemDecoration(ContextCompat.getDrawable(getApplicationContext(),
R.drawable.item_separator)));
但是我如何在Kotlin中进行操作,我也尝试在Android Studio中进行转换,但显示了一些错误.这是我的Decorator类:
but how can I do in Kotlin, I also tried to convert it in Android Studio but shows me a couples of errors. Here is my Decorator class:
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内
then inside your 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
}
如果您在活动内部使用,则使用
If you're using inside an activity then instead use
applicationContext
applicationContext
val decorator = DividerItemDecoration(applicationContext, LinearLayoutManager.VERTICAL)
decorator.setDrawable(ContextCompat.getDrawable(applicationContext, R.drawable.file)!!)
recycler_view.addItemDecoration(decorator)
这篇关于如何在Kotlin中为RecyclerView添加项目分隔线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!