我正在开发一个android应用程序,我正在使用RecyclerView。我需要在RecyclerView中添加一个分隔符。
我试着加上-
recyclerView.addItemDecoration(new
DividerItemDecoration(getActivity(),
DividerItemDecoration.VERTICAL_LIST));
下面是我的XML代码-
<android.support.v7.widget.RecyclerView
android:id="@+id/drawerList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
/>
class ItemOffsetDecoration(
context: Context,
private val paddingLeft: Int,
private val paddingRight: Int
) : RecyclerView.ItemDecoration() {
private var mDivider: Drawable? = null
init {
mDivider = ContextCompat.getDrawable(context, R.drawable.divider_medium)
}
override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
val left = parent.paddingLeft + paddingLeft
val right = parent.width - parent.paddingRight - paddingRight
val childCount = parent.childCount
for (i in 0 until childCount) {
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val top = child.bottom + params.bottomMargin
val bottom = top + (mDivider?.intrinsicHeight ?: 0)
mDivider?.let {
it.setBounds(left, top, right, bottom)
it.draw(c)
}
}
}
}
你只需要在R.drawable.divider_medium中指定一个颜色
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@android:color/black" />
<size
android:height="1dp"
android:width="1dp" />
</shape>
并将它添加到您的recyclerView
recyclerView.addItemDecoration(
ItemOffsetDecoration(
this,
resources.getDimension(resources.getDimension(R.dimen.dp_70).roundToInt()).roundToInt(),
0
)
)
refernce这