我有以下代码,在回收器视图中的项目之间创建分隔线。它在正常模式下工作得很好,但当切换到暗模式时,线条不再可见。如何解决这个问题?
recyclerView.addItemDecoration(DividerItemDecoration(this@MainActivity, LinearLayoutManager.VERTICAL))
您可以尝试使用自定义drawable作为分隔符。如:
val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
val drawable = ResourcesCompat.getDrawable(resources, R.drawable.line_divider, null)
drawable?.let {
recyclerView.addItemDecoration(CustomDivider(this,LinearLayoutManager.VERTICAL,it))
}
CustomDivider类如下:
class CustomDivider(context: Context, orientation: Int, private val mDrawable:Drawable): DividerItemDecoration(context,orientation) {
override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
val left = parent.paddingStart
val right = parent.width - parent.paddingEnd
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 + mDrawable.intrinsicHeight
mDrawable.setBounds(left,top, right, bottom)
mDrawable.draw(c)
}
}
}
以及用作分隔线的drawble:line_divider.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size
android:width="1dp"
android:height="1dp" />
<solid android:color="#D3D3D3" />
有两个选项可以解决您的问题:
- 使用函数dividerItemDecoration.setDrawable()为每个主题(暗/亮)设置自定义绘制
- 覆盖android listDivider属性为每个主题(暗/光)
对于第二个选项,您可以修改您的暗模式分隔符的颜色(例如在文件themes.xml
中),如下所示
<style name="MyAppTheme" parent="Some.Base.Theme.NightMode">
<item name="android:listDivider">@color/my_divider_color_darkmode</item>
</style>
如果我理解正确的话,问题是在黑暗模式下,你的分隔符与你的背景颜色相同,所以分隔符是"不可见的"?
另一个解决方案可能是:在你的回收视图中为单个项目(我假设你已经有了)设置一个布局,并在这个项目的末尾添加分隔符。然后在"资源"中定义分隔符的样式,并在其中传递分隔符的颜色,并为分隔符的亮/暗模式设置两种不同的颜色。
类似:
添加到单个项目布局的末尾
<View
style="@style/Divider" />
然后在样式文件中:
<style name="Divider">
<item name="android:background">@color/colorDivider</item>
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">1dp</item>
</style>
这取决于你如何实现你的暗模式,有两个颜色文件的光和暗模式,其中你定义你的colorDivider