Does anyone know how to tie together a Switch with...
# compose
m
Does anyone know how to tie together a Switch with a Text so that the switch announces the text as it’s focused. Best i can find is using the “contentDescription” semantic property on the switch, and that should announce it, but then the text will also get announced as it’s own thing.
👍 1
b
I’d put a
Modifier.toggleable()
on the parent like so:
Copy code
Row(
  modifier = Modifier.toggleable(
      value = checked,
      onValueChange = { checked = !checked},
      role = Role.Switch
  )
) {
  Switch(
      checked = checked,

      // null prevents the switch from being independently clickable
      onCheckedChange = null 
  )
        
  Text( ... )
}
Modifier.toggleable()
will do a
Modifier.semantics(mergeDescendants = true)
internally, which is the merging behavior that you want. Using
Modifier.toggleable()
instead of
Modifier.semantics()
directly ensures that the entire merged content gets the correct semantics for a switch element in addition to just merging them. This also has the side effect (desired, IMO) of making the text clickable to toggle the switch as well.
☝️ 2
👌 1
l
Then I'd pass indication = null, save one
MutableInteractionSource
(or something?) and pass into both Checkbox and Text(with indication = null.) It would only show indication for Checkbox, but also allows clicking through text. Just like https://raw.githubusercontent.com/lhwdev/covid-selftest-macro/c2db5c40805fb7262aa9c8f7da493a1867c3cb24/app/src/main/java/com/lhwdev/selfTestMacro/ui/utils/TextCheckbox.kt (but I forgot semantic ones so merge with the answer above)
👌 1