I\'d like to round the corners of a view and also change the color of the view based on the contents at runtime.
TextView v = new TextView(context);
v.setTex
Copying @cimlman's comment into a top-level answer for more visibility:
PaintDrawable(Color.CYAN).apply {
setCornerRadius(24f)
}
FYI: ShapeDrawable
(and its subtype, PaintDrawable
) uses default intrinsic width and height of 0. If the drawable does not show up in your usecase, you might have to set the dimensions manually:
PaintDrawable(Color.CYAN).apply {
intrinsicWidth = -1
intrinsicHeight = -1
setCornerRadius(24f)
}
-1
is a magic constant which indicates that a Drawable has no intrinsic width and height of its own (Source).
Here's an example using an extension. This assumes the view has the same width and height.
Need to use a layout change listener to get the view size.
Then you can just call this on a view like this myView.setRoundedBackground(Color.WHITE)
fun View.setRoundedBackground(@ColorInt color: Int) {
addOnLayoutChangeListener(object: View.OnLayoutChangeListener {
override fun onLayoutChange(v: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) {
val shape = GradientDrawable()
shape.cornerRadius = measuredHeight / 2f
shape.setColor(color)
background = shape
removeOnLayoutChangeListener(this)
}
})
}