How to change card_view:cardCornerRadius programmatically
Asked Answered
D

1

40

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.

Deliquesce answered 4/7, 2016 at 10:43 Comment(1)
Are you got any solution ?Kruller
B
96

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) 
Badge answered 4/7, 2016 at 10:47 Comment(9)
Unfortunately not working, get backs to default atrubitesHumiliate
@Sam You need to use a dp to px conversionBandeen
It results in white background around the corners.Rank
I have programmatically generated CardViews and tried adding them in a LinearLayout inside Horizontal ScrollView. but this code doesnot work even when documentation says it should. I know it's been marked correct, but is there anything that I need to look for ?Fatherless
Yes same issue as @SoumyadeepGhosh this is not useful for me. Any other solution ?Kruller
@BhavenShah Have you applied any "background color" to the CardView, rather than "Card Background Colour" ?Fatherless
yes, I applied both the same color. My issue solved by removing background color. Thanks.Kruller
Wondering why setBackgroundColor makes the radius redundant. Would have taken me forever to fix it had I not read the note that you mentioned. ThanksAdenoma
Your clarification with setCardBackgroundColor saves livesUnexpressed

© 2022 - 2024 — McMap. All rights reserved.