Gabriel
03/24/2021, 9:37 PMvar modifier = Modifier
if (isSelected) {
modifier.border(2.dp, Color.White)
}
Gabriel
03/24/2021, 9:38 PMSergey Y.
03/24/2021, 9:39 PMmodifier = modifier.border(2.dp, Color.White)
Gabriel
03/24/2021, 9:40 PMGabriel
03/24/2021, 9:42 PMjava.lang.ClassCastException: androidx.compose.ui.ComposedModifier cannot be cast to androidx.compose.ui.Modifier$Companion
Gabriel
03/24/2021, 9:43 PM@ExperimentalMaterialApi
@Composable
fun MessageRow(loaf: Loaf, editLoafDate: (Loaf) -> Unit, editLoafType: (Loaf) -> Unit, isSelected: Boolean) {
var modifier = Modifier
if (isSelected) {
modifier = modifier.border(2.dp, Color.White) as Modifier.Companion
}
ListItem(
text = {
Text(
text = loaf.updateDate.toString(),
fontWeight = FontWeight.Medium,
fontSize = 20.sp
)
},
trailing = {
IconButton(onClick = { editLoafDate(loaf) }) {
Image(
imageVector = Icons.Outlined.Edit,
contentDescription = "Edit Bread Date",
contentScale = ContentScale.FillBounds,
colorFilter = ColorFilter.tint(Color.White),
modifier = Modifier.fillMaxSize(0.8f)
)
}
},
icon = {
IconButton(onClick = { editLoafType(loaf) }) {
Image(
painter = painterResource(
if (loaf.icon != 0) loaf.icon else R.drawable.bread_slice
),
contentDescription = "Loaf Icon",
contentScale = ContentScale.FillBounds,
)
}
},
modifier = modifier
)
}
Sergey Y.
03/24/2021, 9:47 PMinline fun Modifier.applyIf(
condition: Boolean,
modifier: Modifier.() -> Modifier
) = if (condition) this.then(modifier()) else this
You can use it like
ListItem(...
modifier = Modifier.applyIf(isSelected) { border(2.dp, Color.White) }
}
Gabriel
03/24/2021, 9:59 PMGabriel
03/24/2021, 9:59 PMSergey Y.
03/24/2021, 10:05 PMSean McQuillan [G]
03/24/2021, 10:31 PMModifier.Companion
which is-a Modifier
but is also a distinct class, then later when you try to do re-assignment to Modifier
it fails.
Here's a worky solution given the initial code:
@Composable
fun ModifierTest() {
val (isSelected, setSelected) = remember { mutableStateOf(false)}
var modifier: Modifier = Modifier
if (isSelected) {
modifier = modifier.padding(10.dp).border(2.dp, Color.Cyan)
}
Column(modifier) {
Button(onClick = { setSelected(!isSelected) }) {
Text("Toggle")
}
}
}
And how I'd code it slightly differently to turn the var
into a val
for kotlin hygene
@Composable
fun ModifierTest() {
val (isSelected, setSelected) = remember { mutableStateOf(false)}
val modifier = if (isSelected) {
Modifier.padding(10.dp).border(2.dp, Color.Cyan)
} else {
Modifier
}
Column(modifier) {
Button(onClick = { setSelected(!isSelected) }) {
Text("Toggle")
}
}
}
Sean McQuillan [G]
03/24/2021, 10:33 PMfun ThingWithModifier(modifier: Modifier = Modifier // actually reads Modifier.Companion and upcasts to Modifier)
Sean McQuillan [G]
03/24/2021, 10:33 PMSean McQuillan [G]
03/24/2021, 10:34 PMGabriel
03/25/2021, 5:45 AM