Android中RecyclerView自定义分割线颜色无效问题排查
RecyclerView设置自定义颜色分割线后无法显示的原因及解决办法
问题核心原因是:你直接使用ColorDrawable作为分割线的drawable,但ColorDrawable默认没有设置固有尺寸(高度/宽度),而RecyclerView的DividerItemDecoration需要依赖drawable的固有尺寸来绘制分割线。默认的系统分割线使用的是?android:attr/listDivider这个系统drawable,它本身已经定义了固定的高度和样式,所以能正常显示。
解决方法有两种:
方法1:给ColorDrawable设置固有尺寸
先在res/values/dimens.xml中定义分割线高度:
<dimen name="divider_height">2dp</dimen>
然后给ColorDrawable设置高度(垂直布局用height,水平布局用width):
val recycler = findViewById<RecyclerView>(R.id.recyclerNotifications) recycler.adapter = NotificationsAdapter(titleList) val layoutManager = LinearLayoutManager(this) recycler.layoutManager = layoutManager val dividerItemDecoration = DividerItemDecoration(this, layoutManager.orientation) // 获取分割线高度(dp转像素) val dividerHeight = resources.getDimensionPixelSize(R.dimen.divider_height) val orangeColor = ContextCompat.getColor(this, R.color.orange) val colorDrawable = ColorDrawable(orangeColor) colorDrawable.setIntrinsicHeight(dividerHeight) dividerItemDecoration.setDrawable(colorDrawable) recycler.addItemDecoration(dividerItemDecoration)
方法2:使用ShapeDrawable定义带尺寸的分割线
ShapeDrawable可以更灵活地定义分割线样式,同时指定尺寸:
val recycler = findViewById<RecyclerView>(R.id.recyclerNotifications) recycler.adapter = NotificationsAdapter(titleList) val layoutManager = LinearLayoutManager(this) recycler.layoutManager = layoutManager val dividerItemDecoration = DividerItemDecoration(this, layoutManager.orientation) val shapeDrawable = ShapeDrawable(RectShape()).apply { paint.color = ContextCompat.getColor(this@NotificationsActivity, R.color.orange) intrinsicHeight = resources.getDimensionPixelSize(R.dimen.divider_height) } dividerItemDecoration.setDrawable(shapeDrawable) recycler.addItemDecoration(dividerItemDecoration)
额外提示:
- 若使用水平方向的LinearLayoutManager,需将
intrinsicHeight替换为intrinsicWidth - 推荐用
ContextCompat.getColor()替代resources.getColor(),适配Android 6.0+的颜色资源获取规范
内容的提问来源于stack exchange,提问作者Cool_Coder
相关产品推荐
相关产品推荐

