Skip to content
Tutorials Center
My learning

Topics

Lesson 86 of 104 · Quality, Performance and Security

Accessibility and Localization

Make your Android app usable with TalkBack and in every language: semantics, touch targets, contrast, string resources, plurals, RTL and per-app language settings.

An app that works only for sighted users with steady hands who read English is an app that works for a fraction of the world. About one in six people lives with some disability, many more have a temporary or situational one (a broken wrist, bright sunlight, a noisy train), and most of your potential users do not speak your first language. Accessibility and localization are two sides of the same promise: your app adapts to the person, not the other way round.

This lesson covers both. For accessibility you will learn how TalkBack reads your screen, how Compose semantics describe it, and the rules for touch targets and contrast. For localization you will learn string resources, plurals, right-to-left (RTL) layouts and per-app language settings. It builds on Text, Images and Icons and The Manifest and Resources. Android's accessibility services and resource system need a device, so the real code is read-only. The TryIt blocks are plain-Kotlin stand-ins: a plural-rule resolver for several languages, a contrast and touch-target checker, and a tiny semantics tree like the one TalkBack walks.

How people use your app without looking at it

TalkBack is Android's built-in screen reader. It speaks what is on screen and lets a person explore by touch or by swiping from element to element. Other users rely on Switch Access (operating the phone with one or two buttons), voice control, a braille display, font and display scaling, or color correction. You do not write separate code for each service. They all read the same information: the accessibility tree, an abstract description of your UI as a list of nodes with a role, a label, a state and available actions.

flowchart LR
    A["Your composables"] --> B["Semantics tree<br/>role, label, state, actions"]
    B --> C["TalkBack<br/>speech"]
    B --> D["Switch Access<br/>focus and select"]
    B --> E["Voice Access<br/>say a label to tap"]

Every assistive service reads the same semantics tree that your UI produces.

Compose builds that tree for you from the components you use. A Button with Text("Save") already announces "Save, button, double tap to activate". Your work is to fill the gaps where the default is missing or wrong.

Semantics in Compose

The semantics system attaches meaning to composables. You met contentDescription for images; here are the tools you use most.

Kotlin
// read-only example: needs Jetpack Compose
// 1. Images and icons: describe the meaning, or mark them decorative
Icon(Icons.Default.Delete, contentDescription = "Delete note")
Image(painterResource(R.drawable.divider), contentDescription = null)   // decorative: skipped

// 2. An icon-only button needs a label for the action, not the picture
IconButton(onClick = onShare) {
    Icon(Icons.Default.Share, contentDescription = stringResource(R.string.share_note))
}

// 3. Merge several nodes into one announcement
Row(Modifier.semantics(mergeDescendants = true) {}) {
    Icon(Icons.Default.Star, contentDescription = null)
    Text("4.5 rating, 120 reviews")
}

// 4. Give a custom control a role and state
Box(
    Modifier
        .toggleable(value = checked, role = Role.Switch, onValueChange = onChange)
        .semantics { stateDescription = if (checked) "On" else "Off" }
)

// 5. Headings and live updates
Text("Settings", Modifier.semantics { heading() })
Text(errorText, Modifier.semantics { liveRegion = LiveRegionMode.Polite })

// 6. Custom actions replace a hidden swipe gesture
Modifier.semantics {
    customActions = listOf(
        CustomAccessibilityAction("Archive") { onArchive(); true }
    )
}

A few principles keep your labels useful:

  • Describe purpose, not appearance. "Delete note", not "trash can icon". TalkBack already says "button" or "image", so do not repeat the role.
  • Decorative images get contentDescription = null, so TalkBack does not stop on them.
  • Merge related nodes so a list row is one announcement ("Alice, last message, 5 minutes ago") instead of five separate stops.
  • Headings let a TalkBack user jump through a long screen quickly.
  • Do not hide actions behind gestures only. Swipe to dismiss is invisible to a screen reader, so provide a custom action or a menu.
  • Use clickable(onClickLabel = "Open details") when the default "double tap to activate" would be vague.

You can test it yourself: turn on TalkBack in system settings (or use the Accessibility Scanner app and the Android Studio accessibility checks) and use your app with the screen off. Wherever you get lost, so does a blind user.

A semantics tree as a model

The accessibility tree is just data. This stand-in builds a small tree of nodes and produces the sentence a screen reader would speak for each focusable node: label, then role, then state. It models the idea of semantics (merging, decorative nodes, state announcements), not TalkBack's real speech rules.

Kotlin What a screen reader would say (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The "Before" screen produces stops that say only "image" and "button": a user hears that something is there but not what it does. The "After" screen has fewer stops and each one is meaningful.

Touch targets, text size and contrast

Three measurable rules cover most low-hanging fruit.

Touch targets. Fingers are not pixels. Material guidelines call for interactive elements at least 48 by 48 dp, and Compose's Material components already enforce that minimum around small controls. If you build a custom clickable, make sure it is big enough: a 24 dp icon should get padding or Modifier.minimumInteractiveComponentSize(). Space between neighboring targets matters too.

Text size. Users can scale text up to about 200% in system settings. Always size text in sp, never dp; test with the largest font scale and make sure nothing is clipped or overlapped. Allow layouts to grow or scroll rather than fixing heights.

Contrast. Low-contrast text is hard to read for many people and for everyone outdoors. The WCAG guideline asks for a contrast ratio of at least 4.5:1 for normal text and 3:1 for large text (about 18 sp or 14 sp bold) and for meaningful icons and borders. The ratio comes from each color's relative luminance L, computed from its sRGB channels:

ratio = (L_lighter + 0.05) / (L_darker + 0.05)

Material 3's default color schemes are designed to pass, but custom brand colors often fail, especially gray text on white and text on images.

Never use color alone to convey meaning either. An error shown only by a red border is invisible to a color-blind user; add an icon or text such as "Invalid email".

A contrast and touch-target checker

This stand-in implements the WCAG formula and the 48 dp rule. The math is the real definition, so you can reuse the idea in a unit test for your theme colors.

Kotlin Contrast ratio and touch target check (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Black on white is the maximum possible ratio, 21:1. The gray #767676 is famous as the lightest gray that still passes on white, so it sits right at the line. Lighter grays such as #999999 fail even the relaxed 3:1 limit for large text, so a pale gray is rarely a good choice for anything meaningful. The brand blue with white text passes by a hair, which is a reminder to check custom colors rather than trust your eyes.

String resources: never hard-code text

Localization starts with a rule you already know from The Manifest and Resources: put every user-visible string in res/values/strings.xml, never in code. Each additional language gets its own folder named with a language code, optionally a region:

TEXT
read-only example: resource folders
res/values/strings.xml          default (used when nothing else matches)
res/values-es/strings.xml       Spanish
res/values-pt-rBR/strings.xml   Portuguese, Brazil
res/values-b+sr+Latn/strings.xml   Serbian in Latin script
XML
<!-- read-only example: res/values/strings.xml -->
<resources>
    <string name="app_name">Notes</string>
    <string name="welcome_user">Welcome back, %1$s!</string>
    <string name="storage_used">%1$d of %2$d MB used</string>
</resources>

Use positional placeholders (%1$s, %2$d) rather than %s, because word order differs between languages: a translator may need the second argument first. In Compose you read strings with stringResource(R.string.welcome_user, name).

The default values/ folder must contain every string, because it is the fallback when a device uses a language you did not translate. Rules that save you pain later:

  • Never build sentences by concatenation ("You have " + n + " items"). Grammar does not survive translation. Use one string with placeholders.
  • Format numbers, dates and currency with locale-aware APIs (NumberFormat, DateTimeFormatter, java.text), not by hand. 1,234.5 in English is 1.234,5 in German.
  • Add translator comments in the XML for strings whose meaning is not obvious ("Save" the verb versus "Save" the noun).
  • Leave room. German text is often 30% longer than English, so do not size containers to one language.
  • Mark things that must not be translated with translatable="false".

Plurals

"1 file" and "2 files" look like an easy if (n == 1). In other languages it is not. Russian has different forms for 1, 2 to 4, and 5 or more (with exceptions for 11 to 14); Arabic has six forms; Japanese has only one. Android solves this with plurals resources, which use the CLDR plural categories zero, one, two, few, many and other:

XML
<!-- read-only example: res/values/strings.xml -->
<plurals name="files_selected">
    <item quantity="one">%d file selected</item>
    <item quantity="other">%d files selected</item>
</plurals>
XML
<!-- read-only example: res/values-ru/strings.xml -->
<plurals name="files_selected">
    <item quantity="one">Выбран %d файл</item>
    <item quantity="few">Выбрано %d файла</item>
    <item quantity="many">Выбрано %d файлов</item>
    <item quantity="other">Выбрано %d файла</item>
</plurals>
Kotlin
// read-only example: Compose
Text(pluralStringResource(R.plurals.files_selected, count, count))

The first count selects the form and the second fills the %d. Each language file supplies only the categories its language uses (and always other). You never decide the form yourself: you pass the number and the platform applies the rules of the current locale. zero is also a category, but English does not use it, so write "No files selected" as a separate string when you want it.

A plural resolver for several languages

This stand-in implements simplified CLDR rules for integers in a few languages and picks a category for a number. It shows why one if cannot work and how a resource system picks a form from the locale. Android does this for you using full CLDR data, so you never write it yourself.

Kotlin Plural categories by language (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Look at the Russian block: 1 and 21 are one, 2 and 22 are few, while 5, 11 and 25 are many. And French treats 0 like 1, so "0 fichier" is correct. A hard-coded English rule would produce wrong text in most of the world.

Right-to-left layouts

Arabic, Hebrew, Persian and Urdu read from right to left. In an RTL locale the whole UI mirrors: the back arrow sits on the right, text aligns right, rows flow right to left. Compose handles most of this automatically because it uses start and end instead of left and right: Arrangement.Start, padding(start = 16.dp), Alignment.End. To support RTL:

  • Declare android:supportsRtl="true" in the manifest (the default for new projects).
  • Use start/end everywhere; avoid left/right (in XML, marginStart instead of marginLeft).
  • Mirror directional icons (back arrows, forward arrows) but not icons with a fixed meaning such as a phone or a media-play triangle. Icons.AutoMirrored.Filled.ArrowBack flips automatically.
  • Test with the Force RTL layout direction developer option, or with a pseudo-locale (ar-XB), which also mirrors your layout.
  • Numbers keep their reading direction inside RTL text; let the platform's text engine handle bidirectional text rather than reversing strings yourself.

You can also preview in code: CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) { Screen() } is a handy @Preview trick.

Per-app language

Android 13 introduced per-app language preferences: a user can pick a language for your app that differs from the system language. You opt in by listing the languages you support in a locales.xml file and referencing it from the manifest:

XML
<!-- read-only example: res/xml/locales_config.xml -->
<locale-config xmlns:android="http://schemas.android.com/apk/res/android">
    <locale android:name="en" />
    <locale android:name="es" />
    <locale android:name="ar" />
    <locale android:name="ru" />
</locale-config>
XML
<!-- read-only example: AndroidManifest.xml -->
<application android:localeConfig="@xml/locales_config" ... />

The system then shows your app in Settings, System, Languages, App languages. If you want to offer an in-app language picker, call AppCompatDelegate.setApplicationLocales(LocaleListCompat.forLanguageTags("es")), which works back to older versions with AppCompat. The activity is recreated with the new resources (see Configuration Changes and Saved State), so state must survive recreation. Mention the supported languages in Gradle with androidResources { localeFilters += listOf("en", "es", "ar", "ru") } to keep unused library translations out of your app.

A testing checklist

  • Turn on TalkBack and complete the main flows with the screen off.
  • Run the Accessibility Scanner and Studio's checks; fix missing labels, small targets and low contrast.
  • Set font size and display size to the maximum and check every screen.
  • Switch the device to a long-text language (German), an RTL language (Arabic) and a non-Latin script (Japanese).
  • Use pseudo-locales (en-XA accented, ar-XB mirrored) to catch hard-coded strings and clipped text early.
  • Write Compose tests that assert the semantics (onNodeWithContentDescription, see Testing Compose UI); a failing finder is often a missing label.

Good accessibility and good localization improve the app for everyone. Captions help in a loud room, large tap targets help on a bus, clear labels help voice control, and a layout that tolerates long German text tolerates a user's large font setting too.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What do TalkBack, Switch Access and Voice Access all read?

    Assistive services use the semantics tree of nodes with roles, labels, states and actions. That is why one good description serves all of them.
  2. 2. What should contentDescription be for a purely decorative divider image?

    A null description marks the image as decorative. Describing it would add a pointless stop for screen reader users.
  3. 3. What are the minimum WCAG contrast ratio for normal text and the recommended minimum touch target size?

    Normal text needs 4.5:1 (large text 3:1), and Material guidance asks for interactive elements of at least 48 by 48 dp.
  4. 4. Why should you use plurals resources instead of if (count == 1) in code?

    Russian, Arabic, French and others do not follow English's one/other split. A plurals resource lets each translation list its categories while the platform chooses the form.
  5. 5. Which approach best supports right-to-left languages in Compose?

    Start and end follow the layout direction, so the UI mirrors automatically. Directional icons need to flip too, which the AutoMirrored icons do.

Summary

  • Accessibility services read the semantics tree. Compose builds most of it from your components; you add labels, roles, states, headings and custom actions where needed.
  • Describe purpose not appearance, mark decorative images with null, merge related nodes, and never hide an action behind a gesture only.
  • Use touch targets of at least 48 dp, sp for text, a contrast ratio of 4.5:1 (3:1 for large text), and never rely on color alone.
  • Put all text in string resources with positional placeholders; never concatenate sentences; keep a complete default values/ folder.
  • Use plurals resources with CLDR categories; the platform picks the form for the locale.
  • Use start/end and auto-mirrored icons for RTL, and declare supported languages in locales_config.xml for per-app language.
  • Test with TalkBack, maximum font size, long and RTL languages, and pseudo-locales.
  • Android's accessibility and resource APIs are read-only here; the TryIts model the semantics tree, contrast math and plural rules in plain Kotlin.

Next: Signing and Release Builds