dev_nil
dev_nil

Reputation: 189

How to create an icon in the corner of the android compose card

I want to create something similar to the example below.

Use android compose for this.

enter image description here

Upvotes: 3

Views: 5352

Answers (1)

Thracian
Thracian

Reputation: 66599

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))
}

Upvotes: 8

Related Questions