1

I want to create something similar to the example below.

Use android compose for this.

enter image description here

Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
dev_nil
  • 89
  • 1
  • 8

1 Answers1

7

You can have a toggle button for button on top right and Box to put that button on Image with aligning on top right

@Composable
fun FavoriteButton(
    modifier: Modifier = Modifier,
    color: Color = Color.White
) {

    var isFavorite by remember { mutableStateOf(false) }

    IconToggleButton(
        checked = isFavorite,
        onCheckedChange = {
            isFavorite = !isFavorite
        }
    ) {
        Icon(
            tint = color,
         
            imageVector = if (isFavorite) {
                Icons.Filled.Favorite
            } else {
                Icons.Default.FavoriteBorder
            },
            contentDescription = null
        )
    }

}

@Composable
fun MyComponent(
    imageUrl:String,
    modifier: Modifier = Modifier,
) {
    Box(contentAlignment = Alignment.TopEnd) {

        Image(
            contentScale = ContentScale.None,
            modifier = modifier,
            painter = rememberImagePainter(data = imageUrl),
            contentDescription = null
        )
        
        FavoriteButton(modifier = Modifier.padding(12.dp))

    }
}

rememberImagePainter requires Coil as dependency implementation("io.coil-kt:coil-compose:x.x.x")

and if you think favorite button is smaller than required you can use

    modifier = modifier.graphicsLayer {
        scaleX = 1.3f
        scaleY = 1.3f
    }

on Icon to have bigger heart shape

enter image description here

And if you want a shape behind button you can wrap it inside a Surface

Surface(
    shape = CircleShape,
    modifier = Modifier
        .padding(6.dp)
        .size(32.dp),
    color = Color(0x77000000)
) {
    FavoriteButton(modifier = Modifier.padding(8.dp))
}
Thracian
  • 43,021
  • 16
  • 133
  • 222
  • Thanks. You've helped me a lot – dev_nil Oct 05 '21 at 15:44
  • You didn't use a card tho, it's a workaround using a box instead – G. Ciardini Jan 26 '23 at 23:30
  • @G.Ciardini this is not a workaround. Card uses Surface and Surface is a Box with material modifier and propagateConstraints true. If you check out source code you will see that nothing special with `Card` composable. You can give shapes, borders elevation or click properties as Card by delegating to Surface and Surface by using Box with modifier https://stackoverflow.com/a/73030914/5457853 – Thracian Jan 27 '23 at 03:29