How to change card_view:cardCornerRadius programmatically

Faisal Ahsan picture Faisal Ahsan · Jul 4, 2016 · Viewed 14k times · Source

In my project, I am using RecyclerView in my listing using CardView. In my listing I have to set the corner radius of CardView dynamically based on device.

Is there any way to set cardview corner radius value dynamically?

Thanks.

Answer

natario picture natario · Jul 4, 2016

Use CardView.setRadius(float), see androidx.cardview.

(It is worth noting that this will have no effect if you also invoke setBackgroundColor, make sure to use setCardBackgroundColor instead).

You must specify a pixel size, rather than dp value, e.g. for corner radius of 4dp you can invoke, in Kotlin:

radius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4f, context.resources.displayMetrics)