Last active
May 17, 2025 00:46
-
-
Save rozPierog/1145af6e1f10c9199000828ab4bd6bad to your computer and use it in GitHub Desktop.
Android Glance Widget Corner Radius <12 Compat
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Adds rounded corners for the current view. | |
| * | |
| * On S+ it uses [GlanceModifier.cornerRadius] | |
| * on <S it creates [ShapeDrawable] and sets background | |
| * | |
| * @param cornerRadius [Int] radius set to all corners of the view. | |
| * @param color [Int] value of a color that will be set as background | |
| * @param backgroundAlpha [Float] value of an alpha that will be set to background color - defaults to 1f | |
| */ | |
| fun GlanceModifier.cornerRadiusCompat( | |
| cornerRadius: Int, | |
| @ColorInt color: Int, | |
| @FloatRange(from = 0.0, to = 1.0) backgroundAlpha: Float = 1f, | |
| ): GlanceModifier { | |
| return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { | |
| this.background(Color(color).copy(alpha = backgroundAlpha)) | |
| .cornerRadius(cornerRadius.dp) | |
| } else { | |
| val radii = FloatArray(8) { cornerRadius.toFloat() } | |
| val shape = ShapeDrawable(RoundRectShape(radii, null, null)) | |
| shape.paint.color = ColorUtils.setAlphaComponent(color, (255 * backgroundAlpha).toInt()) | |
| val bitmap = shape.toBitmap(width = 150, height = 75) | |
| this.background(BitmapImageProvider(bitmap)) | |
| } | |
| } | |
| const val cornerRadius = 12 | |
| const val backgroundAlpha = 0.08f | |
| @Composable | |
| fun BackgroundCompat( | |
| modifier: GlanceModifier = GlanceModifier, | |
| onClick: Action, | |
| @ColorRes colorRes: Int, | |
| content: @Composable () -> Unit | |
| ) { | |
| val context = LocalContext.current | |
| val color = context.getColor(colorRes) | |
| Box( | |
| modifier = modifier.cornerRadiusCompat(cornerRadius, color, backgroundAlpha) | |
| .padding(12.dp) | |
| .clickable(onClick) | |
| .width(150.dp) | |
| .height(75.dp), | |
| content = content | |
| ) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment