'Making Favorite button in jetpack compose
my task is to make favorite button with jetpack compose.
On my picture in top left corner I should put favorite icon.
I managed to make picture:
Box(modifier = Modifier.height(200.dp)){
Image(
painter = movie.picture,
contentDescription = "Something",
contentScale = ContentScale.Crop
)
ListItem (
trailing = {
if (movie.isCheckedOff != null) {
Checkbox(
checked = movie.isCheckedOff,
onCheckedChange = { isChecked ->
val newMovieState =
movie.copy(isCheckedOff = isChecked)
onMovieCheckedChange.invoke(newMovieState)
},
modifier = Modifier.padding(8.dp)
)
}
This makes image and does logic for Checkbox ( I don't want to use checkbox). Should I have 2 images and then use one if button is true and another if false. I have problem with displaying favorite picture and then switching it on and off.
Solution 1:[1]
You can do it like this
@Composable
fun FavoriteButton(
modifier: Modifier = Modifier,
color: Color = Color(0xffE91E63)
) {
var isFavorite by remember { mutableStateOf(false) }
IconToggleButton(
checked = isFavorite,
onCheckedChange = {
isFavorite = !isFavorite
}
) {
Icon(
tint = color,
modifier = modifier.graphicsLayer {
scaleX = 1.3f
scaleY = 1.3f
},
imageVector = if (isFavorite) {
Icons.Filled.Favorite
} else {
Icons.Default.FavoriteBorder
},
contentDescription = null
)
}
}
You can change from var isFavorite by remember { mutableStateOf(false) } to states in ViewModel if you want to store favorite state for instance if this is in a LazyColumn.
Add transparent circle behind the button with
Surface(
shape = CircleShape,
modifier = Modifier
.padding(6.dp)
.size(32.dp),
color = Color(0x77000000)
) {
FavoriteButton(modifier = Modifier.padding(8.dp))
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Thracian |

