Switch
controls require specific construction in order to be accessible. Specifically, they must have a wrapping layout to programmatically associate a label and subsume the Switch
's role and toggle handling. These techniques support WCAG Success Criterion 1.3.1 Info and Relationships and Success Criterion 4.1.2 Name, Role, Value.
The required techniques are:
- Wrap the
Switch
and aText
(orIcon
) label in a layout composable (generally aRow
). - Use
Modifier.toggleable()
on the wrapping layout to take over theSwitch
's role andonValueChange
handling. - Null out the
Switch
'sonValueChange
handling. - Resize the
Switch
usingModifier.minimumInteractiveComponentSize()
(Material 3) orModifier.defaultMinSize(minWidth = 48.dp, minHeight = 48.dp)
(Material 2) to maintain its prior size.
For example:
val (isBoldText, setIsBoldText) = remember { mutableStateOf(false) }
Row(
modifier = modifier
.toggleable(
value = isBoldText,
role = Role.Switch,
onValueChange = setIsBoldText
),
verticalAlignment = Alignment.CenterVertically
) {
Text(text = "Bold text", modifier = Modifier.padding(end = 8.dp))
Switch(
checked = isBoldText,
onCheckedChange = null,
modifier = Modifier.minimumInteractiveComponentSize()
)
}
Notes:
- The techniques for
Checkbox
andSwitch
are identical, except for the Role assigned (and layout considerations). - Applying
Modifier.toggleable
to theRow
automatically merges the child descendants' semantics so theRow
is read as a unit in TalkBack. - Nulling the
Switch
'sonCheckedChange
handling removes its automatic sizing, which should generally be restored a sizing modifier as shown. - The hard-coded text shown in these examples is only used for simplicity. Always use externalized string resource references in actual code.
Copyright 2023-2024 CVS Health and/or one of its affiliates
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.