MaterialCardView动态设置strokeColor显示灰色问题咨询
问题描述
在RecyclerView中使用MaterialCardView,每个列表项对应不同重要性,需为其设置对应颜色的描边。
静态XML配置(显示正常):
<com.google.android.material.card.MaterialCardView app:strokeColor="@color/low_importance_green" app:strokeWidth="@dimen/cardview_border_width" app:rippleColor="@color/low_importance_green">
动态设置颜色的Kotlin代码(描边显示异常):
override fun onBindViewHolder(holder: ViewHolder, position: Int) { val colour = when (viewModel.importance){ 1 -> R.color.high_importance_red 2 -> R.color.medium_importance_yellow else -> R.color.low_importance_green } holder.card.setRippleColorResource(colour) holder.card.strokeColor = colour }
静态设置strokeColor时显示正常,但动态设置时描边始终呈灰色(略带紫色),rippleColor则显示正常。怀疑和MaterialTheme有关,询问该现象的原因及解决方法。
原因与解决方法
原因
strokeColor属性需要接收实际的颜色值(ColorInt,即ARGB格式的数值),但你直接传入的是颜色资源ID(比如R.color.high_importance_red只是资源的编号,不是真正的颜色数值)。系统无法将资源ID识别为有效颜色,因此会 fallback 到默认的灰色描边。而setRippleColorResource()是专门接收资源ID的方法,所以可以正常工作。
解决方法
只需将颜色资源ID转换为对应的ColorInt值,或使用MaterialCardView提供的专用方法,两种方式任选其一:
方式一:通过ContextCompat.getColor()转换资源ID
override fun onBindViewHolder(holder: ViewHolder, position: Int) { val colourRes = when (viewModel.importance){ 1 -> R.color.high_importance_red 2 -> R.color.medium_importance_yellow else -> R.color.low_importance_green } val colorInt = ContextCompat.getColor(holder.itemView.context, colourRes) holder.card.setRippleColorResource(colourRes) holder.card.strokeColor = colorInt }
方式二:使用setStrokeColorResource()方法
MaterialCardView提供了直接设置描边颜色资源的方法,无需手动转换:
override fun onBindViewHolder(holder: ViewHolder, position: Int) { val colourRes = when (viewModel.importance){ 1 -> R.color.high_importance_red 2 -> R.color.medium_importance_yellow else -> R.color.low_importance_green } holder.card.setRippleColorResource(colourRes) holder.card.setStrokeColorResource(colourRes) }
内容的提问来源于stack exchange,提问作者Owlon
相关产品推荐
相关产品推荐

