diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index d8900b3..ba1297f 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -22,6 +22,7 @@
"./jetpack-compose/adaptive",
"./jetpack-compose/migration/migrate-xml-views-to-jetpack-compose",
"./jetpack-compose/theming/styles",
+ "./media/media3-cast-integration",
"./navigation/navigation-3",
"./performance/r8-analyzer",
"./play/engage-sdk-integration",
@@ -32,6 +33,7 @@
"./security/android-intent-security",
"./system/edge-to-edge",
"./testing/testing-setup",
+ "./tv/leanback-to-compose-tv-migration",
"./wear/wear-compose-m3",
"./xr/display-glasses-with-jetpack-compose-glimmer"
],
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index f28a37b..13f515a 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -55,6 +55,11 @@
"path": "./jetpack-compose/theming/styles"
}
},
+ {
+ "source": {
+ "path": "./media/media3-cast-integration"
+ }
+ },
{
"source": {
"path": "./navigation/navigation-3"
@@ -105,6 +110,11 @@
"path": "./testing/testing-setup"
}
},
+ {
+ "source": {
+ "path": "./tv/leanback-to-compose-tv-migration"
+ }
+ },
{
"source": {
"path": "./wear/wear-compose-m3"
diff --git a/build-system/agp/agp-9-upgrade/SKILL.md b/build-system/agp/agp-9-upgrade/SKILL.md
index 247b6ee..8ad57ba 100644
--- a/build-system/agp/agp-9-upgrade/SKILL.md
+++ b/build-system/agp/agp-9-upgrade/SKILL.md
@@ -6,7 +6,7 @@ description: Upgrades, or migrates, an Android project to use Android Gradle Plu
license: Complete terms in LICENSE.txt
metadata:
author: Google LLC
- last-updated: '2026-07-23'
+ last-updated: '2026-08-06'
keywords:
- Android Gradle Plugin 9
- AGP 9
@@ -18,23 +18,13 @@ metadata:
## Migration guide
-See the [AGP 9 migration guide](references/android/build/releases/agp-9-0-0-release-notes.md) for the major changes, many
-breaking, in AGP 9 compared to AGP 8.
+See the [AGP 9 migration guide](references/android/build/releases/agp-9-0-0-release-notes.md) for the major changes, many breaking, in AGP 9 compared to AGP 8.
## Requirements
-If the user requests to update or migrate to AGP 9, first check the AGP version
-used in the project. If it is lower than 9, stop and ask the user to run the AGP
-Upgrade Assistant in Android Studio to update to the latest stable version of
-AGP, and confirm when done. The user may also request that this requirement be
-skipped; if this is the case, you should update the version of AGP to the latest
-stable version as part of the AGP 9 migration. See the
-[AGP 9 migration guide](references/android/build/releases/agp-9-0-0-release-notes.md) for how to do this.
+If the user requests to update or migrate to AGP 9, first check the AGP version used in the project. If it is lower than 9, stop and ask the user to run the AGP Upgrade Assistant in Android Studio to update to the latest stable version of AGP, and confirm when done. The user may also request that this requirement be skipped; if this is the case, you should update the version of AGP to the latest stable version as part of the AGP 9 migration. See the [AGP 9 migration guide](references/android/build/releases/agp-9-0-0-release-notes.md) for how to do this.
-Each version of AGP has its own set of compatibilities with other tools, such as
-Gradle, JDK, and Kotlin. The release notes for each of these versions will
-include a **Compatibility** table indicating the minimum versions for these
-tools.
+Each version of AGP has its own set of compatibilities with other tools, such as Gradle, JDK, and Kotlin. The release notes for each of these versions will include a **Compatibility** table indicating the minimum versions for these tools.
Do not use this skill for KMP projects, as they are unsupported.
@@ -44,8 +34,7 @@ If AGP is already at 9 or higher, then do the following:
### Step 1: Update dependencies
-If KSP (`com.google.devtools.ksp`) is used in the project, ensure it is on
-version 2.3.6 or higher.
+If KSP (`com.google.devtools.ksp`) is used in the project, ensure it is on version 2.3.6 or higher.
If Hilt is used in the project, ensure it is on version 2.59.2 or higher.
@@ -57,19 +46,15 @@ See [the guide](references/android/build/migrate-to-built-in-kotlin.md) for deta
See [the guide](references/android/build/releases/agp-9-0-0-release-notes.md) for detailed information.
-See also [gradle-recipes](references/recipes.md) for examples on how to migrate old code to code
-that is compatible with AGP 9 and the new DSL.
+See also [gradle-recipes](references/recipes.md) for examples on how to migrate old code to code that is compatible with AGP 9 and the new DSL.
### Step 4. Migrate kapt to KSP or legacy-kapt
-If KSP (`com.google.devtools.ksp`) or kapt (`org.jetbrains.kotlin.kapt`) are
-used in the project, see [KSP, kapt, and legacy-kapt](references/ksp-kapt.md) for detailed migration
-steps.
+If KSP (`com.google.devtools.ksp`) or kapt (`org.jetbrains.kotlin.kapt`) are used in the project, see [KSP, kapt, and legacy-kapt](references/ksp-kapt.md) for detailed migration steps.
### Step 5. BuildConfig
-If any Android module contains custom BuildConfig fields, see [BuildConfig](references/buildconfig.md)
-for detailed information.
+If any Android module contains custom BuildConfig fields, see [BuildConfig](references/buildconfig.md) for detailed information.
### Step 6. Update gradle.properties
@@ -99,5 +84,4 @@ After migration, verify the following:
## Troubleshooting
-Paparazzi v2.0.0-alpha04 and lower versions have issues with AGP 9. See
-[references/paparazzi-gradle-9.md](references/paparazzi-gradle-9.md) for details.
+Paparazzi v2.0.0-alpha04 and lower versions have issues with AGP 9. See [references/paparazzi-gradle-9.md](references/paparazzi-gradle-9.md) for details.
diff --git a/build-system/agp/agp-9-upgrade/references/android/build/migrate-to-built-in-kotlin.md b/build-system/agp/agp-9-upgrade/references/android/build/migrate-to-built-in-kotlin.md
index 7306e7b..820bf0f 100644
--- a/build-system/agp/agp-9-upgrade/references/android/build/migrate-to-built-in-kotlin.md
+++ b/build-system/agp/agp-9-upgrade/references/android/build/migrate-to-built-in-kotlin.md
@@ -1,33 +1,20 @@
-Android Gradle plugin 9.0 introduces built-in Kotlin support and enables it
-by default. That means you no longer have to apply the
-`org.jetbrains.kotlin.android` (or `kotlin-android`) plugin in your build files
-to compile Kotlin source files.
-With built-in Kotlin, your build files are simpler and you can avoid
-compatibility issues between AGP and the `kotlin-android` plugin.
+Android Gradle plugin 9.0 introduces built-in Kotlin support and enables it by default. That means you no longer have to apply the `org.jetbrains.kotlin.android` (or `kotlin-android`) plugin in your build files to compile Kotlin source files. With built-in Kotlin, your build files are simpler and you can avoid compatibility issues between AGP and the `kotlin-android` plugin.
> [!NOTE]
> **Note:** Built-in Kotlin replaces the `kotlin-android` plugin only. If you are writing a Kotlin Multiplatform (KMP) library module, you still need to apply the `org.jetbrains.kotlin.multiplatform` plugin and the [`com.android.kotlin.multiplatform.library`](https://developer.android.com/kotlin/multiplatform/plugin) plugin. Also, using the `org.jetbrains.kotlin.multiplatform` plugin together with the `com.android.library` or `com.android.application` plugin is no longer allowed when built-in Kotlin is enabled.
## Enable built-in Kotlin
-You need AGP 9.0 or higher to have built-in Kotlin support.
-AGP 9.0 already enables built-in Kotlin for all your modules where you apply
-AGP, so you don't need to do anything to enable it. However, if you previously
-[opted out of built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin#opt-out-of-built-in-kotlin) by setting `android.builtInKotlin=false`
-in the `gradle.properties` file, you need to remove that setting or set it to
-`true`.
+You need AGP 9.0 or higher to have built-in Kotlin support. AGP 9.0 already enables built-in Kotlin for all your modules where you apply AGP, so you don't need to do anything to enable it. However, if you previously [opted out of built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin#opt-out-of-built-in-kotlin) by setting `android.builtInKotlin=false` in the `gradle.properties` file, you need to remove that setting or set it to `true`.
> [!NOTE]
> **Note:** You can also enable built-in Kotlin for [one module at a time](https://developer.android.com/build/migrate-to-built-in-kotlin#module-by-module-migration).
-Built-in Kotlin requires some changes to your project, so after you
-have built-in Kotlin enabled, follow the next steps to migrate your project.
+Built-in Kotlin requires some changes to your project, so after you have built-in Kotlin enabled, follow the next steps to migrate your project.
## Migration steps
-After you upgrade your project from an older AGP version to AGP 9.0 or after
-you manually [enable built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin#enable-built-in-kotlin), you might see the following error
-message:
+After you upgrade your project from an older AGP version to AGP 9.0 or after you manually [enable built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin#enable-built-in-kotlin), you might see the following error message:
Failed to apply plugin 'org.jetbrains.kotlin.android'.
> Cannot add extension with name 'kotlin', as there is an extension already registered with that name.
@@ -37,8 +24,7 @@ message:
Failed to apply plugin 'com.jetbrains.kotlin.android'
> The 'org.jetbrains.kotlin.android' plugin is no longer required for Kotlin support since AGP 9.0.
-This error occurs because built-in Kotlin requires some changes to your project.
-To resolve this error, follow these steps:
+This error occurs because built-in Kotlin requires some changes to your project. To resolve this error, follow these steps:
> [!NOTE]
> **Note:** If you're not yet ready to migrate your project, you can also [opt out of built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin#opt-out-of-built-in-kotlin).
@@ -50,10 +36,7 @@ To resolve this error, follow these steps:
### 1. Remove the `kotlin-android` plugin
-Remove the `org.jetbrains.kotlin.android` (or `kotlin-android`) plugin from
-the module-level build files where you apply it.
-The exact code to remove depends on
-whether you use [version catalogs](https://docs.gradle.org/current/userguide/version_catalogs.html) to declare plugins.
+Remove the `org.jetbrains.kotlin.android` (or `kotlin-android`) plugin from the module-level build files where you apply it. The exact code to remove depends on whether you use [version catalogs](https://docs.gradle.org/current/userguide/version_catalogs.html) to declare plugins.
### With version catalogs
@@ -137,8 +120,7 @@ plugins {
}
```
-If you use version catalogs, also remove the plugin definition from the
-version catalog TOML file (usually `gradle/libs.versions.toml`):
+If you use version catalogs, also remove the plugin definition from the version catalog TOML file (usually `gradle/libs.versions.toml`):
```toml
[plugins]
@@ -147,16 +129,11 @@ kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "KOTLIN_VE
### 2. Migrate the `kotlin-kapt` plugin if necessary
-The `org.jetbrains.kotlin.kapt` (or `kotlin-kapt`) plugin is incompatible with
-built-in Kotlin. If you use `kapt`, we recommend that you
-[migrate your project to KSP](https://developer.android.com/build/migrate-to-ksp).
+The `org.jetbrains.kotlin.kapt` (or `kotlin-kapt`) plugin is incompatible with built-in Kotlin. If you use `kapt`, we recommend that you [migrate your project to KSP](https://developer.android.com/build/migrate-to-ksp).
-If you can't migrate to KSP yet, replace the `kotlin-kapt` plugin with the
-`com.android.legacy-kapt` plugin, using the same version as your Android Gradle
-plugin.
+If you can't migrate to KSP yet, replace the `kotlin-kapt` plugin with the `com.android.legacy-kapt` plugin, using the same version as your Android Gradle plugin.
-For example, with version catalogs, update your version catalog TOML
-file as follows:
+For example, with version catalogs, update your version catalog TOML file as follows:
```toml
[plugins]
@@ -216,8 +193,7 @@ plugins {
### 3. Migrate the `android.kotlinOptions{}` DSL if necessary
-If you use the `android.kotlinOptions{}` DSL, you need to
-migrate it to the [`kotlin.compilerOptions{}`](https://kotlinlang.org/docs/gradle-compiler-options.html#migrate-from-kotlinoptions-to-compileroptions) DSL.
+If you use the `android.kotlinOptions{}` DSL, you need to migrate it to the [`kotlin.compilerOptions{}`](https://kotlinlang.org/docs/gradle-compiler-options.html#migrate-from-kotlinoptions-to-compileroptions) DSL.
For example, update this code:
@@ -274,15 +250,9 @@ kotlin {
### 4. Migrate the `kotlin.sourceSets{}` DSL if necessary
-When you use the `kotlin-android` plugin, AGP lets you add additional Kotlin
-source directories using either the [`android.sourceSets{}`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/AndroidSourceSet) DSL or the
-[`kotlin.sourceSets{}`](https://kotlinlang.org/api/kotlin-gradle-plugin/kotlin-gradle-plugin-api/org.jetbrains.kotlin.gradle.plugin/-kotlin-source-set/) DSL.
-With the `android.sourceSets{}` DSL, you can add the directories to either the
-`AndroidSourceSet.kotlin` set or the `AndroidSourceSet.java` set.
+When you use the `kotlin-android` plugin, AGP lets you add additional Kotlin source directories using either the [`android.sourceSets{}`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/AndroidSourceSet) DSL or the [`kotlin.sourceSets{}`](https://kotlinlang.org/api/kotlin-gradle-plugin/kotlin-gradle-plugin-api/org.jetbrains.kotlin.gradle.plugin/-kotlin-source-set/) DSL. With the `android.sourceSets{}` DSL, you can add the directories to either the `AndroidSourceSet.kotlin` set or the `AndroidSourceSet.java` set.
-With built-in Kotlin, the only supported option is to add the directories to the
-`AndroidSourceSet.kotlin` set using the `android.sourceSets{}` DSL.
-If you use unsupported options, migrate them as follows:
+With built-in Kotlin, the only supported option is to add the directories to the `AndroidSourceSet.kotlin` set using the `android.sourceSets{}` DSL. If you use unsupported options, migrate them as follows:
### Kotlin
@@ -322,10 +292,7 @@ android.sourceSets.named("main") {
}
```
-If you want to add a Kotlin source directory to a specific variant or if the
-directory is generated by a task, you can use the
-[`addStaticSourceDirectory`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/SourceDirectories#addStaticSourceDirectory(kotlin.String)) or [`addGeneratedSourceDirectory`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/SourceDirectories#addGeneratedSourceDirectory(org.gradle.api.tasks.TaskProvider,kotlin.Function1)) methods
-in the [variant API](https://developer.android.com/build/extend-agp#variant-api-artifacts-tasks):
+If you want to add a Kotlin source directory to a specific variant or if the directory is generated by a task, you can use the [`addStaticSourceDirectory`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/SourceDirectories#addStaticSourceDirectory(kotlin.String)) or [`addGeneratedSourceDirectory`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/SourceDirectories#addGeneratedSourceDirectory(org.gradle.api.tasks.TaskProvider,kotlin.Function1)) methods in the [variant API](https://developer.android.com/build/extend-agp#variant-api-artifacts-tasks):
### Kotlin
@@ -347,57 +314,36 @@ androidComponents.onVariants { variant ->
## Report issues
-If you encounter issues after completing the previous steps,
-review the known issues in [issue #438678642](https://issuetracker.google.com/438678642) and give us
-feedback if needed.
+If you encounter issues after completing the previous steps, review the known issues in [issue #438678642](https://issuetracker.google.com/438678642) and give us feedback if needed.
## Opt out of built-in Kotlin
-If you are unable to migrate your project to use built-in Kotlin, set
-`android.builtInKotlin=false` in the `gradle.properties` file to temporarily
-disable it.
-When you do that, the build shows a warning reminding you to migrate to built-in
-Kotlin as you won't be able to disable built-in Kotlin in AGP 10.0.
+If you are unable to migrate your project to use built-in Kotlin, set `android.builtInKotlin=false` in the `gradle.properties` file to temporarily disable it. When you do that, the build shows a warning reminding you to migrate to built-in Kotlin as you won't be able to disable built-in Kotlin in AGP 10.0.
> [!NOTE]
> **Note:** You also need to set `android.newDsl=false` to opt out of the [new DSL](https://developer.android.com/r/tools/new-dsl) because the `kotlin-android` plugin is not compatible with it.
-Once you're ready to migrate your project, [enable built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin#enable-built-in-kotlin)
-and follow the [migration steps](https://developer.android.com/build/migrate-to-built-in-kotlin#migration-steps).
+Once you're ready to migrate your project, [enable built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin#enable-built-in-kotlin) and follow the [migration steps](https://developer.android.com/build/migrate-to-built-in-kotlin#migration-steps).
## Module-by-module migration
-The `android.builtInKotlin` Gradle property lets you enable or disable built-in
-Kotlin for all your modules where you apply AGP.
+The `android.builtInKotlin` Gradle property lets you enable or disable built-in Kotlin for all your modules where you apply AGP.
-If migrating all your modules at once is challenging, you can migrate one module
-at a time:
+If migrating all your modules at once is challenging, you can migrate one module at a time:
-1. Set `android.builtInKotlin=false` in the `gradle.properties` file to
- disable built-in Kotlin for all modules.
+1. Set `android.builtInKotlin=false` in the `gradle.properties` file to disable built-in Kotlin for all modules.
-2. Apply the `com.android.built-in-kotlin` plugin to the module
- you want to enable built-in Kotlin, using the same version as your
- Android Gradle plugin.
+2. Apply the `com.android.built-in-kotlin` plugin to the module you want to enable built-in Kotlin, using the same version as your Android Gradle plugin.
-3. Follow the previous [migration steps](https://developer.android.com/build/migrate-to-built-in-kotlin#migration-steps) to migrate this module to
- built-in Kotlin.
+3. Follow the previous [migration steps](https://developer.android.com/build/migrate-to-built-in-kotlin#migration-steps) to migrate this module to built-in Kotlin.
-4. Once you've migrated all your modules, remove the
- `android.builtInKotlin=false` setting in `gradle.properties`
- and the `com.android.built-in-kotlin` plugin in your build files.
+4. Once you've migrated all your modules, remove the `android.builtInKotlin=false` setting in `gradle.properties` and the `com.android.built-in-kotlin` plugin in your build files.
## Option to selectively disable built-in Kotlin
-Android Gradle plugin 9.0 enables built-in Kotlin for all modules where it is
-applied.
-We recommend disabling built-in Kotlin selectively for modules that don't have
-Kotlin sources in large projects.
-This removes both the Kotlin compilation task, which has a small build
-performance cost, and the automatic dependency on the Kotlin standard library.
+Android Gradle plugin 9.0 enables built-in Kotlin for all modules where it is applied. We recommend disabling built-in Kotlin selectively for modules that don't have Kotlin sources in large projects. This removes both the Kotlin compilation task, which has a small build performance cost, and the automatic dependency on the Kotlin standard library.
-To disable built-in Kotlin for a module,
-set `enableKotlin = false` in that module's build file:
+To disable built-in Kotlin for a module, set `enableKotlin = false` in that module's build file:
### Kotlin
diff --git a/build-system/agp/agp-9-upgrade/references/android/build/releases/agp-9-0-0-release-notes.md b/build-system/agp/agp-9-upgrade/references/android/build/releases/agp-9-0-0-release-notes.md
index d092353..40a5d58 100644
--- a/build-system/agp/agp-9-upgrade/references/android/build/releases/agp-9-0-0-release-notes.md
+++ b/build-system/agp/agp-9-upgrade/references/android/build/releases/agp-9-0-0-release-notes.md
@@ -1,25 +1,16 @@
-Android Gradle plugin 9.0 is a major release that brings API and behavior
-changes.
+Android Gradle plugin 9.0 is a major release that brings API and behavior changes.
-To update to Android Gradle plugin 9.0.1, use the
-[Android Gradle plugin Upgrade Assistant](https://developer.android.com/build/agp-upgrade-assistant). The AGP upgrade assistant helps
-preserve existing behaviors when upgrading your project whenever appropriate, so
-you can upgrade your project to use AGP 9.0 even if you're not ready to
-adopt all the new defaults in AGP 9.0.
+To update to Android Gradle plugin 9.0.1, use the [Android Gradle plugin Upgrade Assistant](https://developer.android.com/build/agp-upgrade-assistant). The AGP upgrade assistant helps preserve existing behaviors when upgrading your project whenever appropriate, so you can upgrade your project to use AGP 9.0 even if you're not ready to adopt all the new defaults in AGP 9.0.
-There are also two agent skills available to make the upgrade process easier.
-For a non-KMP app, try the [AGP 9 upgrade skill](https://github.com/android/skills/tree/main/build/agp/agp-9-upgrade) from the
-Android skills repository. For a KMP app, try the [AGP 9 upgrade
-skill](https://github.com/Kotlin/kotlin-agent-skills/tree/main/skills/kotlin-tooling-agp9-migration) from JetBrains. For more information about using skills
-in Android Studio, see [Extend Agent Mode with skills](https://developer.android.com/studio/gemini/skills).
+There are also two agent skills available to make the upgrade process easier. For a non-KMP app, try the [AGP 9 upgrade skill](https://github.com/android/skills/tree/main/build/agp/agp-9-upgrade) from the Android skills repository. For a KMP app, try the [AGP 9 upgrade skill](https://github.com/Kotlin/kotlin-agent-skills/tree/main/skills/kotlin-tooling-agp9-migration) from JetBrains. For more information about using skills in Android Studio, see [Extend Agent Mode with skills](https://developer.android.com/studio/gemini/skills).
## Compatibility
-The maximum API level that Android Gradle plugin 9.0 supports is API level 36.1.
-Here is other compatibility info:
+The maximum API level that Android Gradle plugin 9.0 supports is API level 36.1. Here is other compatibility info:
+
| | Minimum version | Default version | Notes |
|---:|:---:|:---:|:---:|
@@ -32,52 +23,25 @@ Here is other compatibility info:
## The `android` DSL classes now only implement the new public interfaces
-Over the last several years, we have introduced
-[new interfaces](https://developer.android.com/reference/tools/gradle-api) for our DSL and API in order to
-better control which APIs are public. AGP versions
-7.x and 8.x still used the old DSL types (for example `BaseExtension`) which
-also implemented the new public interfaces, in order to maintain compatibility
-as work progressed on the interfaces.
+Over the last several years, we have introduced [new interfaces](https://developer.android.com/reference/tools/gradle-api) for our DSL and API in order to better control which APIs are public. AGP versions 7.x and 8.x still used the old DSL types (for example `BaseExtension`) which also implemented the new public interfaces, in order to maintain compatibility as work progressed on the interfaces.
-AGP 9.0 uses our new DSL interfaces exclusively,
-and the implementations have changed to new types that are fully hidden. This
-also removes access to the old, deprecated variant API.
+AGP 9.0 uses our new DSL interfaces exclusively, and the implementations have changed to new types that are fully hidden. This also removes access to the old, deprecated variant API.
To update to AGP 9.0, you might need to do the following:
-- **Ensure your project is compatible with [built-in
- Kotlin](https://developer.android.com/build/releases/agp-9-0-0-release-notes#android-gradle-plugin-built-in-kotlin):** The `org.jetbrains.kotlin.android` plugin is not compatible with the new DSL.
-- **Switch KMP projects to the
- [Android Gradle Library Plugin for KMP](https://developer.android.com/kotlin/multiplatform/plugin):**
- Using the `org.jetbrains.kotlin.multiplatform` plugin in the same Gradle
- subproject as the `com.android.library` and `com.android.application` plugins
- is not compatible with the new DSL.
+- **Ensure your project is compatible with [built-in Kotlin](https://developer.android.com/build/releases/agp-9-0-0-release-notes#android-gradle-plugin-built-in-kotlin):** The `org.jetbrains.kotlin.android` plugin is not compatible with the new DSL.
+- **Switch KMP projects to the [Android Gradle Library Plugin for KMP](https://developer.android.com/kotlin/multiplatform/plugin):** Using the `org.jetbrains.kotlin.multiplatform` plugin in the same Gradle subproject as the `com.android.library` and `com.android.application` plugins is not compatible with the new DSL.
> [!NOTE]
> **Note:** The new KMP integration does not support using KMP and the Android Application plugin in the same Gradle subproject. To migrate, extract your Android app to a separate subproject.
-- **Update your build files:**
- While the change of interfaces is meant to keep
- the DSL as similar as possible, there might be
- [some small changes](https://developer.android.com/build/releases/agp-9-0-0-release-notes#android-gradle-plugin-changed-dsl).
+- **Update your build files:** While the change of interfaces is meant to keep the DSL as similar as possible, there might be [some small changes](https://developer.android.com/build/releases/agp-9-0-0-release-notes#android-gradle-plugin-changed-dsl).
-- **Update your custom build logic to reference the new DSL and API:**
- Replace any references to the internal DSL with the public DSL interfaces.
- In most cases this will be a one-to-one replacement.
- Replace any use of the `applicationVariants` and similar APIs with the new
- [`androidComponents` API](https://developer.android.com/build/extend-agp#variant-api-artifacts-tasks).
- This might be more complex, as the `androidComponents` API
- is designed to be more stable to keep plugins compatible longer. Check our
- [Gradle Recipes](https://github.com/android/gradle-recipes/tree/agp-9.0)
- for examples.
+- **Update your custom build logic to reference the new DSL and API:** Replace any references to the internal DSL with the public DSL interfaces. In most cases this will be a one-to-one replacement. Replace any use of the `applicationVariants` and similar APIs with the new [`androidComponents` API](https://developer.android.com/build/extend-agp#variant-api-artifacts-tasks). This might be more complex, as the `androidComponents` API is designed to be more stable to keep plugins compatible longer. Check our [Gradle Recipes](https://github.com/android/gradle-recipes/tree/agp-9.0) for examples.
-- **Update third-party plugins:**
- Some third-party plugins might still depend on interfaces or APIs that are
- no longer exposed. Migrate to versions of those plugins which are compatible
- with AGP 9.0.
+- **Update third-party plugins:** Some third-party plugins might still depend on interfaces or APIs that are no longer exposed. Migrate to versions of those plugins which are compatible with AGP 9.0.
-The switch to the new DSL interfaces prevents plugins and Gradle build scripts
-using various deprecated APIs, including:
+The switch to the new DSL interfaces prevents plugins and Gradle build scripts using various deprecated APIs, including:
| Deprecated API in the `android` block | Function | Replacement |
|---|---|---|
@@ -90,73 +54,43 @@ using various deprecated APIs, including:
| `generatePureSplits` | Generate configuration splits for instant apps. | The ability to ship configuration splits is now built in to Android app bundles. |
| `aidlPackagedList` | AIDL files to package in the AAR to expose it as API for libraries and apps that depend on this library. | This is still exposed on [`LibraryExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/LibraryExtension) but not on the other extension types. |
-If you update to AGP 9.0 and see the following error message, it means that
-your project is still referencing some of the old types:
+If you update to AGP 9.0 and see the following error message, it means that your project is still referencing some of the old types:
java.lang.ClassCastException: class com.android.build.gradle.internal.dsl.ApplicationExtensionImpl$AgpDecorated_Decorated
cannot be cast to class com.android.build.gradle.BaseExtension
-If you are blocked by incompatible third-party plugins, you can opt out and
-get back the old implementations for the DSL, as well as the old variant API.
-While doing this, the new interfaces are also available, and you can still
-update your own build logic to the new API. To opt out, include this line in
-your `gradle.properties` file:
+If you are blocked by incompatible third-party plugins, you can opt out and get back the old implementations for the DSL, as well as the old variant API. While doing this, the new interfaces are also available, and you can still update your own build logic to the new API. To opt out, include this line in your `gradle.properties` file:
android.newDsl=false
-Alternatively, for a more gradual migration, AGP 9.4 lets you opt out individual
-modules. To learn how, see [Variant API module opt-out](https://developer.android.com/build/releases/agp-9-4-0-release-notes#new-dsl-opt-out).
+Alternatively, for a more gradual migration, AGP 9.4 lets you opt out individual modules. To learn how, see [Variant API module opt-out](https://developer.android.com/build/releases/agp-9-4-0-release-notes#new-dsl-opt-out).
-The previous classes are marked as deprecated in AGP 9.0. This means projects
-that opt out of the `newDsl` flag will see deprecation warnings, including on
-the `android` block itself.
+The previous classes are marked as deprecated in AGP 9.0. This means projects that opt out of the `newDsl` flag will see deprecation warnings, including on the `android` block itself.
> [!CAUTION]
> **Caution:** The ability to opt-out will be removed in AGP 10.0 (mid-2026).
-You can also start upgrading to the new APIs before upgrading to AGP 9.0. The
-new interfaces have been present for many AGP versions and so you can have a mix
-of new and old. The [AGP API reference docs](https://developer.android.com/reference/tools/gradle-api) show the API
-surface for each AGP version, and when each class, method and field was
-added.
+You can also start upgrading to the new APIs before upgrading to AGP 9.0. The new interfaces have been present for many AGP versions and so you can have a mix of new and old. The [AGP API reference docs](https://developer.android.com/reference/tools/gradle-api) show the API surface for each AGP version, and when each class, method and field was added.
-We're reaching out to the authors of commonly used plugins to help them adapt
-and release plugins that are fully compatible with the new modes, and will
-continue to enhance the AGP Upgrade Assistant in Android Studio to guide you
-through the migration.
+We're reaching out to the authors of commonly used plugins to help them adapt and release plugins that are fully compatible with the new modes, and will continue to enhance the AGP Upgrade Assistant in Android Studio to guide you through the migration.
-If you find that the new DSL or Variant API are missing capabilities or
-features, please file an [issue](https://issuetracker.google.com/issues/new?component=192708&template=840533) as soon as possible.
+If you find that the new DSL or Variant API are missing capabilities or features, please file an [issue](https://issuetracker.google.com/issues/new?component=192708&template=840533) as soon as possible.
## Built-in Kotlin
-Android Gradle plugin 9.0 introduces built-in Kotlin support and enables it
-by default. That means you no longer have to apply the
-`org.jetbrains.kotlin.android` (or `kotlin-android`) plugin in your build files
-to compile Kotlin source files.
-This simplifies the Kotlin integration with AGP, avoids the use of
-deprecated APIs, and improves performance in some cases.
+Android Gradle plugin 9.0 introduces built-in Kotlin support and enables it by default. That means you no longer have to apply the `org.jetbrains.kotlin.android` (or `kotlin-android`) plugin in your build files to compile Kotlin source files. This simplifies the Kotlin integration with AGP, avoids the use of deprecated APIs, and improves performance in some cases.
-Therefore, when you upgrade your project to AGP 9.0, you need to also
-[migrate to built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin) or [opt out](https://developer.android.com/build/migrate-to-built-in-kotlin#opt-out-of-built-in-kotlin).
+Therefore, when you upgrade your project to AGP 9.0, you need to also [migrate to built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin) or [opt out](https://developer.android.com/build/migrate-to-built-in-kotlin#opt-out-of-built-in-kotlin).
-You can also [selectively disable built-in Kotlin support](https://developer.android.com/build/migrate-to-built-in-kotlin#selectively-disable) for Gradle
-subprojects that don't have Kotlin sources.
+You can also [selectively disable built-in Kotlin support](https://developer.android.com/build/migrate-to-built-in-kotlin#selectively-disable) for Gradle subprojects that don't have Kotlin sources.
## Runtime dependency on Kotlin Gradle plugin
-To provide [built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin) support, Android Gradle plugin 9.0 now has a
-runtime dependency on Kotlin Gradle plugin (KGP) 2.2.10.
-That means you no longer have to declare a KGP version, and if you use a KGP
-version lower than 2.2.10, Gradle will automatically upgrade your KGP version to
-2.2.10.
-Likewise, if you use a KSP version lower than 2.2.10-2.0.2, AGP will upgrade it
-to 2.2.10-2.0.2 to match the KGP version.
+To provide [built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin) support, Android Gradle plugin 9.0 now has a runtime dependency on Kotlin Gradle plugin (KGP) 2.2.10. That means you no longer have to declare a KGP version, and if you use a KGP version lower than 2.2.10, Gradle will automatically upgrade your KGP version to 2.2.10. Likewise, if you use a KSP version lower than 2.2.10-2.0.2, AGP will upgrade it to 2.2.10-2.0.2 to match the KGP version.
### Upgrade to a higher KGP version
-To use a higher version of KGP or KSP, add the following to your top-level build
-file:
+To use a higher version of KGP or KSP, add the following to your top-level build file:
buildscript {
dependencies {
@@ -170,13 +104,9 @@ file:
### Downgrade to a lower KGP version
-You can only downgrade the KGP version if you've
-[opted out of built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin#opt-out-of-built-in-kotlin).
-This is because AGP 9.0 enables built-in Kotlin by default, and built-in Kotlin
-requires KGP 2.2.10 or higher.
+You can only downgrade the KGP version if you've [opted out of built-in Kotlin](https://developer.android.com/build/migrate-to-built-in-kotlin#opt-out-of-built-in-kotlin). This is because AGP 9.0 enables built-in Kotlin by default, and built-in Kotlin requires KGP 2.2.10 or higher.
-To use a lower version of KGP or KSP, declare that version in your top-level
-build file using a [strict version](https://docs.gradle.org/current/userguide/dependency_versions.html#sec:strict-version) declaration:
+To use a lower version of KGP or KSP, declare that version in your top-level build file using a [strict version](https://docs.gradle.org/current/userguide/dependency_versions.html#sec:strict-version) declaration:
buildscript {
dependencies {
@@ -199,17 +129,13 @@ Note that the minimum KGP version you can downgrade to is 2.0.0.
## IDE support for test fixtures
-AGP 9.0 brings full Android Studio IDE support for
-[test fixtures](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/TestFixtures).
+AGP 9.0 brings full Android Studio IDE support for [test fixtures](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/TestFixtures).
## Fused Library Plugin
-The Fused Library Plugin (Preview) lets you publish multiple
-libraries as a single Android Library AAR. This can make it easier for your
-users to depend on your published artifacts.
+The Fused Library Plugin (Preview) lets you publish multiple libraries as a single Android Library AAR. This can make it easier for your users to depend on your published artifacts.
-For information about getting started, see
-[Publish multiple Android libraries as one with Fused Library](https://developer.android.com/build/publish-library/fused-library).
+For information about getting started, see [Publish multiple Android libraries as one with Fused Library](https://developer.android.com/build/publish-library/fused-library).
## Behavior changes
@@ -220,8 +146,7 @@ Android Gradle plugin 9.0 has the following new behaviors:
| Android Gradle plugin 9.0 uses NDK version `r28c` by default. | Consider specifying the NDK version you want to use explicitly. |
| Android Gradle plugin 9.0 by default requires consumers of a library to use the same or higher compile SDK version. | Use the same or higher compile SDK when consuming a library. If this is not possible, or you want to give consumers of a library you publish more time to switch, set [`AarMetadata.minCompileSdk`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/AarMetadata#minCompileSdk()) explicitly. |
-AGP 9.0 includes updates to the following Gradle properties' defaults.
-This gives you the choice to preserve the AGP 8.13 behavior when upgrading:
+AGP 9.0 includes updates to the following Gradle properties' defaults. This gives you the choice to preserve the AGP 8.13 behavior when upgrading:
| Property | Function | Change from AGP 8.13 to AGP 9.0 | Recommendation |
|---|---|---|---|
@@ -236,7 +161,7 @@ This gives you the choice to preserve the AGP 8.13 behavior when upgrading:
| `android.onlyEnableUnitTestForTheTestedBuildType` | Only creates unit test components for the tested build type. In the default project this results in a single unit test for debug, where the previous behavor was to have unit tests run for debug or release. | `false` → `true` | If your project doesn't require tests to run for both debug and release, no change is required. |
| `android.proguard.failOnMissingFiles` | Fails the build with an error if any of the keep files specified in the AGP DSL don't exist on disk. Before this change typos in filenames would result in files being silently ignored. | `false` → `true` | Remove any invalid proguard files declarations |
| `android.r8.optimizedResourceShrinking` | Allows R8 to keep fewer Android resources by considering classes and Android resources together. | `false` → `true` | If your project's keep rules are already complete, no change is required. |
-| `android.r8.strictFullModeForKeepRules` | Allows R8 to keep less by not implicitly keeping the default constructor when a class is kept. That is, `-keep class A` no longer implies `-keep class A { (); }` | `false` → `true` | If your project's keep rules are already complete, no change is required. Replace `-keep class A` with `-keep class A { (); }` in your project's keep rules for any cases where you need the default constructor to be kept. |
+| `android.r8.strictFullModeForKeepRules` | Allows R8 to keep less by not implicitly keeping the default constructor when a class is kept. That is, `-keep class A` no longer implies `-keep class A { (); }` | `false` → `true` | If your project's keep rules are already complete, no change is required. Replace `-keep class A` with `-keep class A { (); }` in your project's keep rules for any cases where you need the default constructor to be kept. |
| `android.defaults.buildfeatures.resvalues` | Enables [`resValues`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/HasAndroidResources#resValues()) in all subprojects | `true` → `false` | Enable `resValues` in only the subprojects that need it by setting the following in those projects' Gradle build files: ``` android { buildFeatures { resValues = true } } ``` |
| `android.defaults.buildfeatures.shaders` | Enables [shader compilation](https://developer.android.com/ndk/guides/graphics/shader-compilers) in all subprojects | `true` → `false` | Enable shader compilation in only the subprojects that contain shaders to be compiled by setting the following in those projects' Gradle build files: ``` android { buildFeatures { shaders = true } } ``` |
| `android.r8.proguardAndroidTxt.disallowed` | In AGP 9.0, `getDefaultProguardFile()` will only support `proguard-android-optimize.txt` rather than `proguard-android.txt`. This is to prevent accidental usage of the `dontoptimize` flag, which is included in `proguard-android.txt`. | `false` → `true` | You can explicitly specify `dontoptimize` in a custom proguardFile if you want to avoid optimization, alongside using `proguard-android-optimize.txt`. Make sure to remove the `dontoptimize` flag from this file if possible, as it reduces R8 optimization benefits. If not, opt out by setting `android.r8.globalOptionsInConsumerRules.disallowed=false`. |
@@ -260,16 +185,9 @@ Android Gradle plugin 9.0 has the following breaking DSL changes:
- The parameterization of [`CommonExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/CommonExtension) has been removed.
- In itself, this is only a source-level breaking change to help
- avoid future source-level breaking changes, but it also means that
- the block methods need to move from [`CommonExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/CommonExtension) to
- [`ApplicationExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/ApplicationExtension), [`LibraryExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/LibraryExtension),
- [`DynamicFeatureExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/DynamicFeatureExtension) and [`TestExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/TestExtension).
+ In itself, this is only a source-level breaking change to help avoid future source-level breaking changes, but it also means that the block methods need to move from [`CommonExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/CommonExtension) to [`ApplicationExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/ApplicationExtension), [`LibraryExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/LibraryExtension), [`DynamicFeatureExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/DynamicFeatureExtension) and [`TestExtension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/TestExtension).
- When upgrading your project to AGP 9.0, refactor Gradle plugin code
- which uses those parameters or the block methods. For example the following
- plugin is updated to remove the type parameter and not rely on the
- removed block methods:
+ When upgrading your project to AGP 9.0, refactor Gradle plugin code which uses those parameters or the block methods. For example the following plugin is updated to remove the type parameter and not rely on the removed block methods:
**AGP 8.13**
@@ -295,8 +213,7 @@ Android Gradle plugin 9.0 has the following breaking DSL changes:
}
}
- For plugins which target a range of AGP versions, using the getter directly
- is binary compatible with AGP versions lower than 9.0.
+ For plugins which target a range of AGP versions, using the getter directly is binary compatible with AGP versions lower than 9.0.
## Removed DSL
@@ -304,50 +221,37 @@ Android Gradle plugin 9.0 removes:
- [`AndroidSourceSet.jni`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/AndroidSourceSet#jni(kotlin.Function1)), because it was not functional.
-- [`AndroidSourceSet.wearAppConfigurationName`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/AndroidSourceSet#wearAppConfigurationName()), as it relates to the
- removed embedded Wear OS app support.
+- [`AndroidSourceSet.wearAppConfigurationName`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/AndroidSourceSet#wearAppConfigurationName()), as it relates to the removed embedded Wear OS app support.
- [`BuildType.isRenderscriptDebuggable`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/BuildType#isRenderscriptDebuggable()), because it was not functional.
-- [`DependencyVariantSelection`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/DependencyVariantSelection). It is replaced By
- [`DependencySelection`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/DependencySelection), which is exposed as
- [`kotlin.android.localDependencySelection`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/KotlinMultiplatformAndroidLibraryExtension#localDependencySelection(kotlin.Function1))
+- [`DependencyVariantSelection`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/DependencyVariantSelection). It is replaced By [`DependencySelection`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/DependencySelection), which is exposed as [`kotlin.android.localDependencySelection`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/KotlinMultiplatformAndroidLibraryExtension#localDependencySelection(kotlin.Function1))
-- [`Installation.installOptions(String)`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/Installation#installOptions(kotlin.String)). It is replaced by the
- mutable property of [`Installation.installOptions`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/Installation#installOptions()).
+- [`Installation.installOptions(String)`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/Installation#installOptions(kotlin.String)). It is replaced by the mutable property of [`Installation.installOptions`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/Installation#installOptions()).
- The experimental, but never stabilized [`PostProcessing`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/PostProcessing) block.
-- [`ProductFlavor.setDimension`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/ProductFlavor#setDimension(kotlin.String)), which is replaced by the
- [`dimension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/ProductFlavor#dimension()) property
+- [`ProductFlavor.setDimension`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/ProductFlavor#setDimension(kotlin.String)), which is replaced by the [`dimension`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/dsl/ProductFlavor#dimension()) property
-- `LanguageSplitOptions`, which was only useful for
- [Google Play Instant](https://developer.android.com/topic/google-play-instant), which is deprecated.
+- `LanguageSplitOptions`, which was only useful for [Google Play Instant](https://developer.android.com/topic/google-play-instant), which is deprecated.
-- [`DensitySplit`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/DensitySplit), because the feature is no longer supported.
- Replacement is to use [App Bundles](https://developer.android.com/guide/app-bundle).
+- [`DensitySplit`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/dsl/DensitySplit), because the feature is no longer supported. Replacement is to use [App Bundles](https://developer.android.com/guide/app-bundle).
## Removed APIs
Android Gradle plugin 9.0 removes:
-- [`AndroidComponentsExtension.finalizeDSl`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/AndroidComponentsExtension#finalizeDSl(org.gradle.api.Action)). It is replaced by
- [`finalizeDsl`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/DslLifecycle#finalizeDsl(kotlin.Function1))
+- [`AndroidComponentsExtension.finalizeDSl`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/AndroidComponentsExtension#finalizeDSl(org.gradle.api.Action)). It is replaced by [`finalizeDsl`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/DslLifecycle#finalizeDsl(kotlin.Function1))
-- [`Component.transformClassesWith`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/Component#transformClassesWith(java.lang.Class,com.android.build.api.instrumentation.InstrumentationScope,kotlin.Function1)). It is replaced by
- [`Instrumentation.transformClassesWith`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/Instrumentation#transformClassesWith(java.lang.Class,com.android.build.api.instrumentation.InstrumentationScope,kotlin.Function1))
+- [`Component.transformClassesWith`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/Component#transformClassesWith(java.lang.Class,com.android.build.api.instrumentation.InstrumentationScope,kotlin.Function1)). It is replaced by [`Instrumentation.transformClassesWith`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/Instrumentation#transformClassesWith(java.lang.Class,com.android.build.api.instrumentation.InstrumentationScope,kotlin.Function1))
-- [`Component.setAsmFramesComputationMode`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/Component#setAsmFramesComputationMode(com.android.build.api.instrumentation.FramesComputationMode)). It is replaced by
- [`Instrumentation.setAsmFramesComputationMode`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/Instrumentation#setAsmFramesComputationMode(com.android.build.api.instrumentation.FramesComputationMode))
+- [`Component.setAsmFramesComputationMode`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/Component#setAsmFramesComputationMode(com.android.build.api.instrumentation.FramesComputationMode)). It is replaced by [`Instrumentation.setAsmFramesComputationMode`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/Instrumentation#setAsmFramesComputationMode(com.android.build.api.instrumentation.FramesComputationMode))
-- [`ComponentBuilder.enabled`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/ComponentBuilder#enabled()). It is replaced by
- [`ComponentBuilder.enable`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/ComponentBuilder#enable()).
+- [`ComponentBuilder.enabled`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/ComponentBuilder#enabled()). It is replaced by [`ComponentBuilder.enable`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/ComponentBuilder#enable()).
-- [`DependenciesInfoBuilder.includedInApk`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/DependenciesInfoBuilder#includedInApk()). Is is replaced by
- [`includeInApk`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/DependenciesInfoBuilder#includeInApk())
+- [`DependenciesInfoBuilder.includedInApk`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/DependenciesInfoBuilder#includedInApk()). Is is replaced by [`includeInApk`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/DependenciesInfoBuilder#includeInApk())
-- [`DependenciesInfoBuilder.includedInBundle`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/DependenciesInfoBuilder#includedInBundle()). Is is replaced by
- [`includeInBundle`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/DependenciesInfoBuilder#includeInBundle())
+- [`DependenciesInfoBuilder.includedInBundle`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/DependenciesInfoBuilder#includedInBundle()). Is is replaced by [`includeInBundle`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/DependenciesInfoBuilder#includeInBundle())
- [`GeneratesApk.targetSdkVersion`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/GeneratesApk#targetSdkVersion()). Is is replaced by [`targetSdk`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/GeneratesApk#targetSdk())
@@ -357,43 +261,25 @@ Android Gradle plugin 9.0 removes:
- [`Variant.targetSdkVersion`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/Variant#targetSdkVersion()). Is is replaced by [`targetSdk`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/Variant#targetSdk())
-- [`Variant.unitTest`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/Variant#unitTest()), as it was not applicable to the
- [`com.android.test`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/gradle/TestPlugin) plugin.
- `unitTest` is available on [`VariantBuilder`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/VariantBuilder) subtypes extending
- [`HasUnitTest`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/HasUnitTest).
+- [`Variant.unitTest`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/Variant#unitTest()), as it was not applicable to the [`com.android.test`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/gradle/TestPlugin) plugin. `unitTest` is available on [`VariantBuilder`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/VariantBuilder) subtypes extending [`HasUnitTest`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/HasUnitTest).
-- [`VariantBuilder.targetSdk`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/VariantBuilder#targetSdk()) and [`targetSdkPreview`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/VariantBuilder#targetSdkPreview()),
- as they were not meaningful in libraries. Use
- [`GeneratesApkBuilder.targetSdk`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/GeneratesApkBuilder#targetSdk()) or
- [`GeneratesApkBuilder.targetSdkPreview`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/GeneratesApkBuilder#targetSdkPreview())
- instead.
+- [`VariantBuilder.targetSdk`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/VariantBuilder#targetSdk()) and [`targetSdkPreview`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/VariantBuilder#targetSdkPreview()), as they were not meaningful in libraries. Use [`GeneratesApkBuilder.targetSdk`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/GeneratesApkBuilder#targetSdk()) or [`GeneratesApkBuilder.targetSdkPreview`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/GeneratesApkBuilder#targetSdkPreview()) instead.
-- [`VariantBuilder.enableUnitTest`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/VariantBuilder#enableUnitTest()), as it was not applicable to the
- [`com.android.test`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/gradle/TestPlugin) plugin.
- `enableUnitTest` is available on [`VariantBuilder`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/VariantBuilder) subtypes extending
- [`HasUnitTestBuilder`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/HasUnitTestBuilder).
+- [`VariantBuilder.enableUnitTest`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/VariantBuilder#enableUnitTest()), as it was not applicable to the [`com.android.test`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/gradle/TestPlugin) plugin. `enableUnitTest` is available on [`VariantBuilder`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/VariantBuilder) subtypes extending [`HasUnitTestBuilder`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/HasUnitTestBuilder).
-- [`VariantBuilder.unitTestEnabled`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/VariantBuilder#unitTestEnabled()) is removed in favor of the more
- consistently
- named [`enableUnitTest`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/HasUnitTestBuilder#enableUnitTest()) on the [`VariantBuilder`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/VariantBuilder) subtypes
- extending [`HasUnitTestBuilder`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/HasUnitTestBuilder).
+- [`VariantBuilder.unitTestEnabled`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/VariantBuilder#unitTestEnabled()) is removed in favor of the more consistently named [`enableUnitTest`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/HasUnitTestBuilder#enableUnitTest()) on the [`VariantBuilder`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/VariantBuilder) subtypes extending [`HasUnitTestBuilder`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/HasUnitTestBuilder).
- [`VariantOutput.enable`](https://developer.android.com/reference/tools/gradle-api/8.13/com/android/build/api/variant/VariantOutput#enable()). Is is replaced by [`enabled`](https://developer.android.com/reference/tools/gradle-api/9.0/com/android/build/api/variant/VariantOutput#enabled())
- The deprecated and disabled `FeaturePlugin` and `FeatureExtension`.
-- The deprecated and disabled `BaseExtension.registerTransform` APIs, which
- only remained to allow compiling against the latest AGP version while
- targeting running on AGP 4.2 or lower.
+- The deprecated and disabled `BaseExtension.registerTransform` APIs, which only remained to allow compiling against the latest AGP version while targeting running on AGP 4.2 or lower.
## Removed Gradle properties
-The following Gradle properties were initially added as ways to globally
-disable features that were enabled by default.
+The following Gradle properties were initially added as ways to globally disable features that were enabled by default.
-These features have been disabled by default since AGP 8.0 or lower. Enable
-these features in only the sub-projects that use them for a more efficient
-build.
+These features have been disabled by default since AGP 8.0 or lower. Enable these features in only the sub-projects that use them for a more efficient build.
| Property | Function | Replacement |
|---|---|---|
@@ -404,8 +290,7 @@ build.
AGP 9.0 throws an error if you set the following Gradle properties.
-The [Android Gradle plugin Upgrade Assistant](https://developer.android.com/build/agp-upgrade-assistant) won't upgrade projects to
-AGP 9.0 that use these properties.
+The [Android Gradle plugin Upgrade Assistant](https://developer.android.com/build/agp-upgrade-assistant) won't upgrade projects to AGP 9.0 that use these properties.
| Property | Function |
|---|---|
@@ -418,11 +303,7 @@ The following R8 changes are included in AGP 9.0.0.
### New configuration option `-processkotlinnullchecks`
-We've added the new R8 option `-processkotlinnullchecks` to configure R8 for
-processing Kotlin null checks. The option takes a mandatory argument that must
-be one of the following three values: `keep`, `remove_message` and `remove`.
-The option processes the following null checks added by the Kotlin
-compiler:
+We've added the new R8 option `-processkotlinnullchecks` to configure R8 for processing Kotlin null checks. The option takes a mandatory argument that must be one of the following three values: `keep`, `remove_message` and `remove`. The option processes the following null checks added by the Kotlin compiler:
class kotlin.jvm.internal.Intrinsics {
void checkNotNull(java.lang.Object);
@@ -442,118 +323,73 @@ compiler:
void checkNotNullParameter(java.lang.Object, java.lang.String);
}
-The option values, ordered from the weakest to the strongest, have the
-following effect:
+The option values, ordered from the weakest to the strongest, have the following effect:
- `keep` doesn't change the checks.
- `remove_message` rewrites each check method call to a call to `getClass()` on the first argument of the call (effectively keeping the null check, but without any message).
- `remove` completely removes the checks.
-By default R8
-uses `remove_message`. Any specification of `-processkotlinnullchecks`
-will override that. If specified multiple times the strongest value is
-used.
+By default R8 uses `remove_message`. Any specification of `-processkotlinnullchecks` will override that. If specified multiple times the strongest value is used.
### Stop propagating keep info to companion methods
-When keep rules match interface methods that are subject to desugaring,
-R8 previously internally transferred the *disallow optimization* and *disallow
-shrinking* bits to the synthesized companion methods.
+When keep rules match interface methods that are subject to desugaring, R8 previously internally transferred the *disallow optimization* and *disallow shrinking* bits to the synthesized companion methods.
-Starting with AGP 9.0, keep rules no longer apply to
-companion methods. This is consistent with the fact that keep rules are
-not applicable to other compiler synthesized fields/methods/classes.
+Starting with AGP 9.0, keep rules no longer apply to companion methods. This is consistent with the fact that keep rules are not applicable to other compiler synthesized fields/methods/classes.
-By transferring the *disallow optimization* and *disallow shrinking* bits to
-the companion methods, the following use case was previously supported:
+By transferring the *disallow optimization* and *disallow shrinking* bits to the companion methods, the following use case was previously supported:
1. Compile a library with `default`/`static`/`private` interface methods to DEX with `minSdk` \< 24 and rules that keep the interface methods.
2. Compile an app with the library on classpath and `-applymapping`.
3. Merge the app and the library.
-Note that this only works with `-applymapping` since the `disallow
-obfuscation` bit is not transferred to the companion methods---that is, the
-companion classes generated from step 1 would have obfuscated method
-names.
+Note that this only works with `-applymapping` since the `disallow obfuscation` bit is not transferred to the companion methods---that is, the companion classes generated from step 1 would have obfuscated method names.
-Going forward this use case is no longer supported for `minSdk` \<
-24. The workaround is to do the following:
+Going forward this use case is no longer supported for `minSdk` \< 24. The workaround is to do the following:
1. Desugar the library with `default`/`static`/`private` interface methods to class files with `minSdk` \< 24.
2. Compile the desugared artifact using R8 and rules that keep the interface methods on the companion classes.
3. Compile the app with the library on classpath.
4. Merge the app and the desugared artifact.
-Another side effect of this is that it is no longer possible to keep the
-inner class and enclosing method attributes for anonymous and local classes
-inside interface companion methods.
+Another side effect of this is that it is no longer possible to keep the inner class and enclosing method attributes for anonymous and local classes inside interface companion methods.
### Change the default emitted source file to `r8-map-id-`
This change is in AGP starting from 8.12.0.
-The default emitted source file attribute for a class changes from
-`SourceFile` to `r8-map-id-` when retracing is required (that is,
-when either obfuscation or optimization is enabled).
+The default emitted source file attribute for a class changes from `SourceFile` to `r8-map-id-` when retracing is required (that is, when either obfuscation or optimization is enabled).
-Given an obfuscated stack trace, the new source file attribute makes it
-possible to extract the ID of the mapping file that is required for
-retracing, which can be used to support
-[automated retracing of stack traces in Logcat](https://developer.android.com/studio/preview/features#logcat-retrace).
+Given an obfuscated stack trace, the new source file attribute makes it possible to extract the ID of the mapping file that is required for retracing, which can be used to support [automated retracing of stack traces in Logcat](https://developer.android.com/studio/preview/features#logcat-retrace).
-If a custom source file attribute is used (`-renamesourcefileattribute`)
-this custom source file attribute continues to take precedence.
+If a custom source file attribute is used (`-renamesourcefileattribute`) this custom source file attribute continues to take precedence.
-In ProGuard compatibility mode (when `gradle.properties` contains
-`android.enableR8.fullMode=false`), emitting a source file attribute of
-`r8-map-id-` only takes effect if the `SourceFile`
-attribute is *not* kept. Apps that use ProGuard compatibility mode and want
-to include the mapping file ID in their stack traces should remove
-`-keepattributes SourceFile` (or migrate to R8 full mode).
+In ProGuard compatibility mode (when `gradle.properties` contains `android.enableR8.fullMode=false`), emitting a source file attribute of `r8-map-id-` only takes effect if the `SourceFile` attribute is *not* kept. Apps that use ProGuard compatibility mode and want to include the mapping file ID in their stack traces should remove `-keepattributes SourceFile` (or migrate to R8 full mode).
-The map ID used in `r8-map-id-` is the full map hash, and not a 7
-character prefix of the map hash which was previously used.
+The map ID used in `r8-map-id-` is the full map hash, and not a 7 character prefix of the map hash which was previously used.
### Enable use of minimized synthetic names in L8 desugaring
-The name of synthetic classes generated by D8 normally contains the substring
-`$$ExternalSynthetic` that tells you that this is a synthetic generated by D8.
-Moreover, the name of the synthetic also encodes the synthetic kind (for
-example, `Backport`, `Lambda`). This has a negative impact on the resulting DEX
-size, since the class names take up more space in the string pool.
+The name of synthetic classes generated by D8 normally contains the substring `$$ExternalSynthetic` that tells you that this is a synthetic generated by D8. Moreover, the name of the synthetic also encodes the synthetic kind (for example, `Backport`, `Lambda`). This has a negative impact on the resulting DEX size, since the class names take up more space in the string pool.
-AGP 9.0 configures L8 (core library desugaring) so that the DEX
-file containing all `j$` classes uses a new shortened class name format
-for synthetic classes. The new class name uses a numeric ID (for example, `$1`).
+AGP 9.0 configures L8 (core library desugaring) so that the DEX file containing all `j$` classes uses a new shortened class name format for synthetic classes. The new class name uses a numeric ID (for example, `$1`).
### Remove support for `-addconfigurationdebugging`
-AGP 9.0 removes support for `-addconfigurationdebugging`. The compiler now
-reports a warning if the flag is used.
+AGP 9.0 removes support for `-addconfigurationdebugging`. The compiler now reports a warning if the flag is used.
### Remove support for generating L8 rules from D8/R8
-This change is only relevant for developers using the D8/R8 command line or
-APIs directly.
+This change is only relevant for developers using the D8/R8 command line or APIs directly.
-R8 9.0 removes support for generating keep rules for L8 from D8 and R8.
-You should instead use `TraceReferences` for this purpose.
+R8 9.0 removes support for generating keep rules for L8 from D8 and R8. You should instead use `TraceReferences` for this purpose.
-More specifically, the methods
-`D8Command.builder.setDesugaredLibraryKeepRuleConsumer` and
-`R8Command.Builder.setDesugaredLibraryKeepRuleConsumer` are removed, and the
-support for `--desugared-lib-pg-conf-output` is removed from the command line
-options of D8 and R8.
+More specifically, the methods `D8Command.builder.setDesugaredLibraryKeepRuleConsumer` and `R8Command.Builder.setDesugaredLibraryKeepRuleConsumer` are removed, and the support for `--desugared-lib-pg-conf-output` is removed from the command line options of D8 and R8.
## Fixed issues
### Android Gradle plugin 9.0.0
-| Fixed Issues ||
-|---|---|
-| **Android Gradle Plugin** | |---| | [Issue #171293712](https://issuetracker.google.com/issues/171293712) Feature Request: Inject ideal AGP version as a property | | [Issue #443976533](https://issuetracker.google.com/issues/443976533) Stabilize SingleArtifact.VERSION_CONTROL_INFO_FILE | | [Issue #223643506](https://issuetracker.google.com/issues/223643506) androidTest connectedCheck logcat output is broken | | [Issue #386221070](https://issuetracker.google.com/issues/386221070) Built-in Kotlin support in AGP should not synchronize with the Kotlin sourcesets | | [Issue #460094802](https://issuetracker.google.com/issues/460094802) missingDimensionStrategy prefers a flavor maching its own name even from an unrelated dimension | | [Issue #386221070](https://issuetracker.google.com/issues/386221070) Built-in Kotlin support in AGP should not synchronize with the Kotlin sourcesets | | [Issue #471410336](https://issuetracker.google.com/issues/471410336) AGP 9.0.0-rc01 doesn't resolve Kotlin libraries via kotlin() function | | [Issue #450851465](https://issuetracker.google.com/issues/450851465) Built-in-kotlin does not publish kotlin-stdlib dependency constraint in maven pom | | [Issue #420592288](https://issuetracker.google.com/issues/420592288) Add a test case for divergence between compileSdk and targetSdk | | [Issue #449153004](https://issuetracker.google.com/issues/449153004) empty resConfigs value leads to obscure aapt error | | [Issue #447375921](https://issuetracker.google.com/issues/447375921) Pure Java project have dependency on kotlin stdlib. | | [Issue #368600704](https://issuetracker.google.com/issues/368600704) Remove deprecated KotlinMultiplatformAndroidCompilationBuilder properties in AGP 9.0 | | [Issue #445209309](https://issuetracker.google.com/issues/445209309) \`com.android.tools.build:gradle:9.0.0-alpha05\` should have an api dependency on KGP and gradle-api | | [Issue #452645779](https://issuetracker.google.com/issues/452645779) Rename com.android.experimental.built-in-kotlin Gradle plugin | | [Issue #446220448](https://issuetracker.google.com/issues/446220448) AGP9: \`variant.sources.kotlin!!.addGeneratedSourceDirectory()\` is not working | | [Issue #448450771](https://issuetracker.google.com/issues/448450771) Aar metadata checks on compile Sdk uses the old DSL | | [Issue #441523448](https://issuetracker.google.com/issues/441523448) Remove deprecated \`com.android.build.api.dsl.ManagedDevices.devices\` property | | [Issue #386221070](https://issuetracker.google.com/issues/386221070) Built-in Kotlin support in AGP should not synchronize with the Kotlin sourcesets | | [Issue #433758231](https://issuetracker.google.com/issues/433758231) Fail android library publishing if consumer keep file contains -dontobfuscate | | [Issue #241955408](https://issuetracker.google.com/issues/241955408) No Options to Print Mapping for Optimized Resources | | [Issue #436595826](https://issuetracker.google.com/issues/436595826) Make it an error to call finalizeDsl after this phase has been passed | | [Issue #457089670](https://issuetracker.google.com/issues/457089670) AGP initializes jetifier config even when jetifier is disabled | | [Issue #452246814](https://issuetracker.google.com/issues/452246814) built in kotlin does not add kotlinStdlib as a compile time dependency when \`kotlin.stdlib.default.dependency\` is true to module and pom files | | [Issue #442250902](https://issuetracker.google.com/issues/442250902) New optimizaation DSL does not create configuration.txt by default | | [Issue #443587266](https://issuetracker.google.com/issues/443587266) AGP 8.13.0 fails to verify nav graph in a module | | [Issue #444260628](https://issuetracker.google.com/issues/444260628) AGP uses deprecated Gradle API: multi-string notation | | [Issue #347732357](https://issuetracker.google.com/issues/347732357) Warn users trying to use legacy multidex library with minSdkVersion \>=21 | | [Issue #333831734](https://issuetracker.google.com/issues/333831734) A build fails if there are code generation tasks | | [Issue #446123111](https://issuetracker.google.com/issues/446123111) With \`android.builtInKotlin=false\` and \`android.newDsl=false\` and \`android.enableLegacyVariantApi=false\`, using \`kotlin-android\` plugin will fail with "API 'applicationVariants' is obsolete" | | [Issue #443037365](https://issuetracker.google.com/issues/443037365) Built-in Kotlin fails to resolve unversioned kotlin-stdlib when kotlin.stdlib.default.dependency=false | | [Issue #445967244](https://issuetracker.google.com/issues/445967244) DexData opens a file without closing, preventing cleanup | | [Issue #368609737](https://issuetracker.google.com/issues/368609737) AndroidSourceDirectorySet should stop extending PatternFilterable in AGP 9.0 | | [Issue #389707041](https://issuetracker.google.com/issues/389707041) Test Fixture Error in test only modules | | [Issue #353249347](https://issuetracker.google.com/issues/353249347) Incorrect error when using context receivers in test fixtures | | [Issue #351046197](https://issuetracker.google.com/issues/351046197) Incorrect IDE errors for Kotlin code in testFixtures | | [Issue #446889652](https://issuetracker.google.com/issues/446889652) \`legacy-kapt\` plugin skips annotation processing unlike \`kotlin-kapt\` | | [Issue #446492061](https://issuetracker.google.com/issues/446492061) compileSdkSpec.minorApiLevel is not working with SettingsExtension | | [Issue #429253579](https://issuetracker.google.com/issues/429253579) \[fused lib - public\] Generated fused library does not include sources | | [Issue #149770867](https://issuetracker.google.com/issues/149770867) extractNativeLibs and useEmbeddedDex should not be coming from the manifest | | [Issue #449114518](https://issuetracker.google.com/issues/449114518) Warnings from R8 in AGP 9.0.0-alpha09 | | [Issue #368426598](https://issuetracker.google.com/issues/368426598) Remove deprecated AndroidSourceSet.jni in AGP 9.0 | | [Issue #368484483](https://issuetracker.google.com/issues/368484483) Remove Installation.installOptions() in AGP 9.0 | | [Issue #368482484](https://issuetracker.google.com/issues/368482484) Remove BuildType.isRenderscriptDebuggable in AGP 9.0. | | [Issue #428646179](https://issuetracker.google.com/issues/428646179) Remove android.defaults.buildfeatures.renderscript | | [Issue #436887358](https://issuetracker.google.com/issues/436887358) \`com.android.kotlin.multiplatform.library\` crashes with Gradle Managed Devices | | [Issue #428645763](https://issuetracker.google.com/issues/428645763) Remove \`android.defaults.buildfeatures.aidl\` defaults gradle.properties flags | | [Issue #294183018](https://issuetracker.google.com/issues/294183018) Fail build when proguard file does not exist | | [Issue #254305041](https://issuetracker.google.com/issues/254305041) remove buildconfig defaults gradle.properties flags | | [Issue #280674230](https://issuetracker.google.com/issues/280674230) Change the app's targetSdk default value to be based on compileSdk instead of minSdk | | [Issue #436878535](https://issuetracker.google.com/issues/436878535) When \`isIncludeAndroidResources\` is enabled, \`process{Variant}UnitTestManifest\` fails to merge tools:overrideLibrary usages in AGP 8.12.0 | | [Issue #411739086](https://issuetracker.google.com/issues/411739086) AGP causing deprecation warnings in Gradle for JVM test tasks | | [Issue #235457021](https://issuetracker.google.com/issues/235457021) DependencyReportTask is incompatible with the configuration cache | | [Issue #369246556](https://issuetracker.google.com/issues/369246556) Switch default source/target Java version from Java 8 to Java 11 in AGP 9.0 | | [Issue #258855275](https://issuetracker.google.com/issues/258855275) Flip android.useAndroidX default to true | | [Issue #442763200](https://issuetracker.google.com/issues/442763200) Better exception when applying kapt plugin with built-in Kotlin. | | [Issue #441679226](https://issuetracker.google.com/issues/441679226) android.proguard.failOnMissingFiles is not working for consumerProguardFiles | | [Issue #443051391](https://issuetracker.google.com/issues/443051391) Update Kotlin Gradle plugin dependency to 2.2.10 | | [Issue #429981132](https://issuetracker.google.com/issues/429981132) Create KotlinJvmAndroidCompilation using KGP API | | [Issue #442869731](https://issuetracker.google.com/issues/442869731) Kotlin explicit API mode applied to test sources | |
-| **Lint** | |---| | [Issue #430991549](https://issuetracker.google.com/issues/430991549) AGP 8.11.0: lintAnalyzeRelease task crashes when applying .gradle.kts files with apply(from = "...") | | [Issue #441536820](https://issuetracker.google.com/issues/441536820) Lint ChecksSdkIntAtLeast Check does not check if the annotated value is correct | | [Issue #446696613](https://issuetracker.google.com/issues/446696613) Built-in Kotlin does not add .kotlin_module to META-INF | | [Issue #449031505](https://issuetracker.google.com/issues/449031505) Lint classpath contains duplicate classes at different versions | | [Issue #448148350](https://issuetracker.google.com/issues/448148350) Overriding private resources workaround not working (tools:override = "true") | | [Issue #405676712](https://issuetracker.google.com/issues/405676712) Bug: removal of unused resources doesn't also remove the translations of them, and doesn't ask about it either | | [Issue #440415636](https://issuetracker.google.com/issues/440415636) Lint throwing warning "Could not clean up K2 caches" | | [Issue #440415636](https://issuetracker.google.com/issues/440415636) Lint throwing warning "Could not clean up K2 caches" | |
-| **Lint Integration** | |---| | [Issue #460068798](https://issuetracker.google.com/issues/460068798) AndroidLintAnalysisTask cache misses across different JDK vendors or minor versions due to systemPropertyInputs.javaVersion differences | | [Issue #444447002](https://issuetracker.google.com/issues/444447002) Lint automatically uses latest installed SDK despite compileSdk, doesn't register as task input and breaks caching | |
-| **Shrinker (R8)** | |---| | [Issue #454927488](https://issuetracker.google.com/issues/454927488) R8 optimized resource shrinking silently fails if using final resource IDs | |
+Fixed Issues **Android Gradle Plugin** [Issue #171293712](https://issuetracker.google.com/issues/171293712) Feature Request: Inject ideal AGP version as a property [Issue #443976533](https://issuetracker.google.com/issues/443976533) Stabilize SingleArtifact.VERSION_CONTROL_INFO_FILE [Issue #223643506](https://issuetracker.google.com/issues/223643506) androidTest connectedCheck logcat output is broken [Issue #386221070](https://issuetracker.google.com/issues/386221070) Built-in Kotlin support in AGP should not synchronize with the Kotlin sourcesets [Issue #460094802](https://issuetracker.google.com/issues/460094802) missingDimensionStrategy prefers a flavor maching its own name even from an unrelated dimension [Issue #386221070](https://issuetracker.google.com/issues/386221070) Built-in Kotlin support in AGP should not synchronize with the Kotlin sourcesets [Issue #471410336](https://issuetracker.google.com/issues/471410336) AGP 9.0.0-rc01 doesn't resolve Kotlin libraries via kotlin() function [Issue #450851465](https://issuetracker.google.com/issues/450851465) Built-in-kotlin does not publish kotlin-stdlib dependency constraint in maven pom [Issue #420592288](https://issuetracker.google.com/issues/420592288) Add a test case for divergence between compileSdk and targetSdk [Issue #449153004](https://issuetracker.google.com/issues/449153004) empty resConfigs value leads to obscure aapt error [Issue #447375921](https://issuetracker.google.com/issues/447375921) Pure Java project have dependency on kotlin stdlib. [Issue #368600704](https://issuetracker.google.com/issues/368600704) Remove deprecated KotlinMultiplatformAndroidCompilationBuilder properties in AGP 9.0 [Issue #445209309](https://issuetracker.google.com/issues/445209309) \`com.android.tools.build:gradle:9.0.0-alpha05\` should have an api dependency on KGP and gradle-api [Issue #452645779](https://issuetracker.google.com/issues/452645779) Rename com.android.experimental.built-in-kotlin Gradle plugin [Issue #446220448](https://issuetracker.google.com/issues/446220448) AGP9: \`variant.sources.kotlin!!.addGeneratedSourceDirectory()\` is not working [Issue #448450771](https://issuetracker.google.com/issues/448450771) Aar metadata checks on compile Sdk uses the old DSL [Issue #441523448](https://issuetracker.google.com/issues/441523448) Remove deprecated \`com.android.build.api.dsl.ManagedDevices.devices\` property [Issue #386221070](https://issuetracker.google.com/issues/386221070) Built-in Kotlin support in AGP should not synchronize with the Kotlin sourcesets [Issue #433758231](https://issuetracker.google.com/issues/433758231) Fail android library publishing if consumer keep file contains -dontobfuscate [Issue #241955408](https://issuetracker.google.com/issues/241955408) No Options to Print Mapping for Optimized Resources [Issue #436595826](https://issuetracker.google.com/issues/436595826) Make it an error to call finalizeDsl after this phase has been passed [Issue #457089670](https://issuetracker.google.com/issues/457089670) AGP initializes jetifier config even when jetifier is disabled [Issue #452246814](https://issuetracker.google.com/issues/452246814) built in kotlin does not add kotlinStdlib as a compile time dependency when \`kotlin.stdlib.default.dependency\` is true to module and pom files [Issue #442250902](https://issuetracker.google.com/issues/442250902) New optimizaation DSL does not create configuration.txt by default [Issue #443587266](https://issuetracker.google.com/issues/443587266) AGP 8.13.0 fails to verify nav graph in a module [Issue #444260628](https://issuetracker.google.com/issues/444260628) AGP uses deprecated Gradle API: multi-string notation [Issue #347732357](https://issuetracker.google.com/issues/347732357) Warn users trying to use legacy multidex library with minSdkVersion \>=21 [Issue #333831734](https://issuetracker.google.com/issues/333831734) A build fails if there are code generation tasks [Issue #446123111](https://issuetracker.google.com/issues/446123111) With \`android.builtInKotlin=false\` and \`android.newDsl=false\` and \`android.enableLegacyVariantApi=false\`, using \`kotlin-android\` plugin will fail with "API 'applicationVariants' is obsolete" [Issue #443037365](https://issuetracker.google.com/issues/443037365) Built-in Kotlin fails to resolve unversioned kotlin-stdlib when kotlin.stdlib.default.dependency=false [Issue #445967244](https://issuetracker.google.com/issues/445967244) DexData opens a file without closing, preventing cleanup [Issue #368609737](https://issuetracker.google.com/issues/368609737) AndroidSourceDirectorySet should stop extending PatternFilterable in AGP 9.0 [Issue #389707041](https://issuetracker.google.com/issues/389707041) Test Fixture Error in test only modules [Issue #353249347](https://issuetracker.google.com/issues/353249347) Incorrect error when using context receivers in test fixtures [Issue #351046197](https://issuetracker.google.com/issues/351046197) Incorrect IDE errors for Kotlin code in testFixtures [Issue #446889652](https://issuetracker.google.com/issues/446889652) \`legacy-kapt\` plugin skips annotation processing unlike \`kotlin-kapt\` [Issue #446492061](https://issuetracker.google.com/issues/446492061) compileSdkSpec.minorApiLevel is not working with SettingsExtension [Issue #429253579](https://issuetracker.google.com/issues/429253579) \[fused lib - public\] Generated fused library does not include sources [Issue #149770867](https://issuetracker.google.com/issues/149770867) extractNativeLibs and useEmbeddedDex should not be coming from the manifest [Issue #449114518](https://issuetracker.google.com/issues/449114518) Warnings from R8 in AGP 9.0.0-alpha09 [Issue #368426598](https://issuetracker.google.com/issues/368426598) Remove deprecated AndroidSourceSet.jni in AGP 9.0 [Issue #368484483](https://issuetracker.google.com/issues/368484483) Remove Installation.installOptions() in AGP 9.0 [Issue #368482484](https://issuetracker.google.com/issues/368482484) Remove BuildType.isRenderscriptDebuggable in AGP 9.0. [Issue #428646179](https://issuetracker.google.com/issues/428646179) Remove android.defaults.buildfeatures.renderscript [Issue #436887358](https://issuetracker.google.com/issues/436887358) \`com.android.kotlin.multiplatform.library\` crashes with Gradle Managed Devices [Issue #428645763](https://issuetracker.google.com/issues/428645763) Remove \`android.defaults.buildfeatures.aidl\` defaults gradle.properties flags [Issue #294183018](https://issuetracker.google.com/issues/294183018) Fail build when proguard file does not exist [Issue #254305041](https://issuetracker.google.com/issues/254305041) remove buildconfig defaults gradle.properties flags [Issue #280674230](https://issuetracker.google.com/issues/280674230) Change the app's targetSdk default value to be based on compileSdk instead of minSdk [Issue #436878535](https://issuetracker.google.com/issues/436878535) When \`isIncludeAndroidResources\` is enabled, \`process{Variant}UnitTestManifest\` fails to merge tools:overrideLibrary usages in AGP 8.12.0 [Issue #411739086](https://issuetracker.google.com/issues/411739086) AGP causing deprecation warnings in Gradle for JVM test tasks [Issue #235457021](https://issuetracker.google.com/issues/235457021) DependencyReportTask is incompatible with the configuration cache [Issue #369246556](https://issuetracker.google.com/issues/369246556) Switch default source/target Java version from Java 8 to Java 11 in AGP 9.0 [Issue #258855275](https://issuetracker.google.com/issues/258855275) Flip android.useAndroidX default to true [Issue #442763200](https://issuetracker.google.com/issues/442763200) Better exception when applying kapt plugin with built-in Kotlin. [Issue #441679226](https://issuetracker.google.com/issues/441679226) android.proguard.failOnMissingFiles is not working for consumerProguardFiles [Issue #443051391](https://issuetracker.google.com/issues/443051391) Update Kotlin Gradle plugin dependency to 2.2.10 [Issue #429981132](https://issuetracker.google.com/issues/429981132) Create KotlinJvmAndroidCompilation using KGP API [Issue #442869731](https://issuetracker.google.com/issues/442869731) Kotlin explicit API mode applied to test sources **Lint** [Issue #430991549](https://issuetracker.google.com/issues/430991549) AGP 8.11.0: lintAnalyzeRelease task crashes when applying .gradle.kts files with apply(from = "...") [Issue #441536820](https://issuetracker.google.com/issues/441536820) Lint ChecksSdkIntAtLeast Check does not check if the annotated value is correct [Issue #446696613](https://issuetracker.google.com/issues/446696613) Built-in Kotlin does not add .kotlin_module to META-INF [Issue #449031505](https://issuetracker.google.com/issues/449031505) Lint classpath contains duplicate classes at different versions [Issue #448148350](https://issuetracker.google.com/issues/448148350) Overriding private resources workaround not working (tools:override = "true") [Issue #405676712](https://issuetracker.google.com/issues/405676712) Bug: removal of unused resources doesn't also remove the translations of them, and doesn't ask about it either [Issue #440415636](https://issuetracker.google.com/issues/440415636) Lint throwing warning "Could not clean up K2 caches" [Issue #440415636](https://issuetracker.google.com/issues/440415636) Lint throwing warning "Could not clean up K2 caches" **Lint Integration** [Issue #460068798](https://issuetracker.google.com/issues/460068798) AndroidLintAnalysisTask cache misses across different JDK vendors or minor versions due to systemPropertyInputs.javaVersion differences [Issue #444447002](https://issuetracker.google.com/issues/444447002) Lint automatically uses latest installed SDK despite compileSdk, doesn't register as task input and breaks caching **Shrinker (R8)** [Issue #454927488](https://issuetracker.google.com/issues/454927488) R8 optimized resource shrinking silently fails if using final resource IDs
\ No newline at end of file
diff --git a/build-system/agp/agp-9-upgrade/references/buildconfig.md b/build-system/agp/agp-9-upgrade/references/buildconfig.md
index e4e19b6..773fcd8 100644
--- a/build-system/agp/agp-9-upgrade/references/buildconfig.md
+++ b/build-system/agp/agp-9-upgrade/references/buildconfig.md
@@ -1,5 +1,4 @@
-When an Android module contains custom BuildConfig fields, the following steps
-are necessary to ensure a correct build.
+When an Android module contains custom BuildConfig fields, the following steps are necessary to ensure a correct build.
### Step 1: Enable the buildConfig build feature
@@ -37,11 +36,9 @@ In custom build-logic using `CommonExtension`:
### Step 2: Migrate to the new API
-Use the **addCustomBuildConfigFields** recipe from the [gradle-recipes](https://developer.android.com/agents/skills/build-system/agp/agp-9-upgrade/references/recipes)
-repository.
+Use the **addCustomBuildConfigFields** recipe from the [gradle-recipes](https://developer.android.com/agents/skills/build-system/agp/agp-9-upgrade/references/recipes) repository.
-**IMPORTANT:** For `BuildConfigField`s with a type of `String`, the `value` field
-*must* include quotation marks as part of the String. For example:
+**IMPORTANT:** For `BuildConfigField`s with a type of `String`, the `value` field *must* include quotation marks as part of the String. For example:
BuildConfigField(
type = "String",
@@ -49,6 +46,4 @@ repository.
comment = "Optional comment",
)
-It is an **error** if the `value` field doesn't include quotation marks as
-part of the String. For example, `value = "Some value"` **is an error** . This is
-because the `value` is written out literally.
\ No newline at end of file
+It is an **error** if the `value` field doesn't include quotation marks as part of the String. For example, `value = "Some value"` **is an error** . This is because the `value` is written out literally.
\ No newline at end of file
diff --git a/build-system/agp/agp-9-upgrade/references/ksp-kapt.md b/build-system/agp/agp-9-upgrade/references/ksp-kapt.md
index e8a5d33..2dacb96 100644
--- a/build-system/agp/agp-9-upgrade/references/ksp-kapt.md
+++ b/build-system/agp/agp-9-upgrade/references/ksp-kapt.md
@@ -1,39 +1,23 @@
-When migrating to built-in Kotlin, it is important to consider usage of `kapt`
-and the `org.jetbrains.kotlin.kapt` (also known as the `kotlin("kapt")`) plugin.
-The goal is to migrate as many `kapt` usages to `ksp` as possible.
+When migrating to built-in Kotlin, it is important to consider usage of `kapt` and the `org.jetbrains.kotlin.kapt` (also known as the `kotlin("kapt")`) plugin. The goal is to migrate as many `kapt` usages to `ksp` as possible.
Follow these steps when migrating `kapt`:
## 1. Remove all references to the `org.jetbrains.kotlin.kapt` plugin
-The `org.jetbrains.kotlin.kapt` (also known as `kotlin("kapt")`) plugin is
-incompatible with built-in Kotlin. Remove it when migrating to built-in Kotlin.
+The `org.jetbrains.kotlin.kapt` (also known as `kotlin("kapt")`) plugin is incompatible with built-in Kotlin. Remove it when migrating to built-in Kotlin.
## 2. Check each usage of `kapt`
-Check each usage of `kapt` to see if it is compatible with `ksp`. To check if a
-dependency is compatible with `ksp`, inspect the dependency's jar. For it to be
-compatible with `ksp`, the jar must have a file,
-`services/com.google.devtools.ksp.processing.SymbolProcessorProvider`. If it
-does not, it is **incompatible** with `ksp`.
+Check each usage of `kapt` to see if it is compatible with `ksp`. To check if a dependency is compatible with `ksp`, inspect the dependency's jar. For it to be compatible with `ksp`, the jar must have a file, `services/com.google.devtools.ksp.processing.SymbolProcessorProvider`. If it does not, it is **incompatible** with `ksp`.
-For example, the `androidx.room:room-compiler` library is compatible with KSP
-since version 2.3.0-beta02. We can verify this by finding the jar file in the
-Gradle caches directory, which is typically located at
-`~/.gradle/caches/modules-2/files-2.1/` on Linux and Mac. In this specific case,
-the `androidx.room:room-compiler` dependency is located at
-`~/.gradle/caches/modules-2/files-2.1/androidx.room/room-compiler/`.
+For example, the `androidx.room:room-compiler` library is compatible with KSP since version 2.3.0-beta02. We can verify this by finding the jar file in the Gradle caches directory, which is typically located at `~/.gradle/caches/modules-2/files-2.1/` on Linux and Mac. In this specific case, the `androidx.room:room-compiler` dependency is located at `~/.gradle/caches/modules-2/files-2.1/androidx.room/room-compiler/`.
-More generally, you can find a dependency by looking in
-`~/.gradle/caches/modules-2/files-2.1/group-name/artifact-name/`.
+More generally, you can find a dependency by looking in `~/.gradle/caches/modules-2/files-2.1/group-name/artifact-name/`.
## 3. Migrate to KSP where possible
-For each usage of `kapt` that is compatible with `ksp`, use `ksp`. The prior
-step explains how to check compatibility.
+For each usage of `kapt` that is compatible with `ksp`, use `ksp`. The prior step explains how to check compatibility.
## 4. Apply legacy-kapt
-If a Gradle module has `kapt` dependencies that cannot be migrated to `ksp`
-because they are incompatible (see step 2), then leave that dependency alone and
-apply the `com.android.legacy-kapt` plugin.
\ No newline at end of file
+If a Gradle module has `kapt` dependencies that cannot be migrated to `ksp` because they are incompatible (see step 2), then leave that dependency alone and apply the `com.android.legacy-kapt` plugin.
\ No newline at end of file
diff --git a/build-system/agp/agp-9-upgrade/references/paparazzi-gradle-9.md b/build-system/agp/agp-9-upgrade/references/paparazzi-gradle-9.md
index a20da2a..97a65bc 100644
--- a/build-system/agp/agp-9-upgrade/references/paparazzi-gradle-9.md
+++ b/build-system/agp/agp-9-upgrade/references/paparazzi-gradle-9.md
@@ -1,19 +1,10 @@
-If Paparazzi is used in the project, update it to version 2.0.0-alpha04 or
-higher.
+If Paparazzi is used in the project, update it to version 2.0.0-alpha04 or higher.
-Paparazzi version 2.0.0-alpha04 and lower is not fully compatible with Gradle
-9, and Gradle 9 is required by AGP 9. This means that, without workarounds,
-projects that use Paparazzi v2.0.0-alpha04 and lower cannot migrate to AGP 9.
+Paparazzi version 2.0.0-alpha04 and lower is not fully compatible with Gradle 9, and Gradle 9 is required by AGP 9. This means that, without workarounds, projects that use Paparazzi v2.0.0-alpha04 and lower cannot migrate to AGP 9.
-At time of writing, there are no higher versions of Paparazzi. That is,
-v2.0.0-alpha04 is the latest release.
+At time of writing, there are no higher versions of Paparazzi. That is, v2.0.0-alpha04 is the latest release.
-The issue is due to Paparazzi using internal classes from Gradle that tend to
-move in breaking ways without warning. This specific issue is related to HTML
-test reports. To work around it, disable those HTML test reports. Here
-are two examples of how to do this, one for Kotlin DSL and the other for Groovy
-DSL. Any module that has the paparazzi plugin (`app.cash.paparazzi`) applied
-must apply one of these two workarounds.
+The issue is due to Paparazzi using internal classes from Gradle that tend to move in breaking ways without warning. This specific issue is related to HTML test reports. To work around it, disable those HTML test reports. Here are two examples of how to do this, one for Kotlin DSL and the other for Groovy DSL. Any module that has the paparazzi plugin (`app.cash.paparazzi`) applied must apply one of these two workarounds.
Kotlin DSL:
diff --git a/build-system/agp/agp-9-upgrade/references/recipes.md b/build-system/agp/agp-9-upgrade/references/recipes.md
index d3ecc74..a5d9856 100644
--- a/build-system/agp/agp-9-upgrade/references/recipes.md
+++ b/build-system/agp/agp-9-upgrade/references/recipes.md
@@ -1,6 +1,4 @@
-When migrating to AGP's new DSL, any Gradle code (plugins or logic in build
-scripts) that relied on the old DSL will stop working. Such code must be
-migrated.
+When migrating to AGP's new DSL, any Gradle code (plugins or logic in build scripts) that relied on the old DSL will stop working. Such code must be migrated.
## Guidelines
@@ -8,14 +6,9 @@ migrated.
- **DO NOT** use AGP internals in migrated code.
- **DO** use only public APIs in migrated code.
-In some cases, there is a one-to-one replacement for the old code. Some examples
-are in [the AGP 9.0.0 release notes](https://developer.android.com/build/releases/agp-9-0-0-release-notes).
+In some cases, there is a one-to-one replacement for the old code. Some examples are in [the AGP 9.0.0 release notes](https://developer.android.com/build/releases/agp-9-0-0-release-notes).
-In other cases, there is no direct one-to-one replacement. For these situations,
-the [gradle-recipes repo](https://github.com/android/gradle-recipes) is a great resource. You can checkout one of its
-AGP 9.x branches, such as `agp-9.0`, `agp-9.1`, or `agp-9.2`. These branches
-contain recipes for common situations in Android projects. The following table
-lists the compatibility for recipes for each version of AGP.
+In other cases, there is no direct one-to-one replacement. For these situations, the [gradle-recipes repo](https://github.com/android/gradle-recipes) is a great resource. You can checkout one of its AGP 9.x branches, such as `agp-9.0`, `agp-9.1`, or `agp-9.2`. These branches contain recipes for common situations in Android projects. The following table lists the compatibility for recipes for each version of AGP.
## Compatibility table
@@ -56,7 +49,4 @@ In the old DSL, an APK could be renamed very simply. Here's an example:
}
}
-However, with AGP 9 and the new DSL, `applicationVariants` is no longer
-available. You must instead react to artifact creation using the
-`androidComponents.onVariants` API. A complete example of this is available in
-the **gradle-recipes** repository in the `listenToArtifacts` recipe.
\ No newline at end of file
+However, with AGP 9 and the new DSL, `applicationVariants` is no longer available. You must instead react to artifact creation using the `androidComponents.onVariants` API. A complete example of this is available in the **gradle-recipes** repository in the `listenToArtifacts` recipe.
\ No newline at end of file
diff --git a/camera/camerax/SKILL.md b/camera/camerax/SKILL.md
index 6ae6ca1..b9ec31a 100644
--- a/camera/camerax/SKILL.md
+++ b/camera/camerax/SKILL.md
@@ -7,7 +7,7 @@ description: Provide technical guidance for Android camera development with Came
license: Complete terms in LICENSE.txt
metadata:
author: Google LLC
- last-updated: '2026-07-07'
+ last-updated: '2026-08-06'
keywords:
- recipe
- Android
@@ -26,20 +26,17 @@ metadata:
- ImageAnalysis.
---
-This skill provides procedural guidance and standard patterns for building
-camera applications on Android, with a focus on CameraX, including its
-`Camera2Interop` utilities, and Media3 integrations.
+This skill provides procedural guidance and standard patterns for building camera applications on Android, with a focus on CameraX, including its `Camera2Interop` utilities, and Media3 integrations.
## Core workflows
### Handling immutable API patterns
-Various Android camera and media APIs, especially CameraX `VideoCapture`, use a
-**fluent, immutable builder-like pattern** where methods return a new instance.
-Failing to reassign these results in settings, such as audio, being ignored.
+Various Android camera and media APIs, especially CameraX `VideoCapture`, use a **fluent, immutable builder-like pattern** where methods return a new instance. Failing to reassign these results in settings, such as audio, being ignored.
**Pattern: Reassignment is required**
+
```kotlin
// WRONG
@@ -62,6 +59,7 @@ run {
pending = pending.withAudioEnabled() // Reassignment
val active = pending.start(exec, listener)
}
+
```
@@ -77,9 +75,7 @@ When migrating legacy camera codebases to the CameraX Jetpack library:
### Comprehensive feature blueprinting
-For multi-step features that involve multiple files and hardware-level wiring,
-follow the [Structural Blueprinting](references/expert-blueprints.md) approach to avoid
-system timeouts. Such complex features include:
+For multi-step features that involve multiple files and hardware-level wiring, follow the [Structural Blueprinting](references/expert-blueprints.md) approach to avoid system timeouts. Such complex features include:
- **Manual controls** : Break down into the `ViewModel` state, the controller layer, and the `Camera2Interop` wiring in the session.
- **RAW capture**: Separate JPEG and RAW output configurations into discrete build steps.
@@ -106,20 +102,16 @@ See [modern-apis](references/modern-apis.md) for current recommendations.
### Code quality and architectural rules
-Adhere to the following Android ecosystem standard patterns when building your
-camera implementations:
+Adhere to the following Android ecosystem standard patterns when building your camera implementations:
- **Testing, fakes over mocks** : Avoid mocking libraries like `Mockito`, especially for multi-step CameraX interfaces like `ImageProxy`. Build "Fakes" to verify state rather than unreliable implementation details.
- **Google Truth assertions** : Use `assertThat` over standard `JUnit` assertions like `assertEquals` for improved readability.
- **Explicit test runners** : Always define an explicit `@RunWith` for test classes to ensure the CI environment executes them correctly.
-- **Semantic UI merging** : When building custom camera controls in Compose, such as a button with an `Icon` and `Text`, use `semantics {
- mergeDescendants = true }` to ensure screen readers announce them as a single, coherent unit.
+- **Semantic UI merging** : When building custom camera controls in Compose, such as a button with an `Icon` and `Text`, use `semantics { mergeDescendants = true }` to ensure screen readers announce them as a single, coherent unit.
## Hardware and device diversity
-Camera apps run on a wide variety of hardware, from mobile phones and
-foldables to tablets, laptops, and even smart appliances. Have consideration
-for the specific hardware the app is running on.
+Camera apps run on a wide variety of hardware, from mobile phones and foldables to tablets, laptops, and even smart appliances. Have consideration for the specific hardware the app is running on.
- **Form factors**: Account for screen size and orientation changes on foldables and tablets.
- **Multi-camera arrays**: Some devices have a rear-facing camera and a front-facing camera. Other devices have multiple rear-facing cameras, such as wide-angle and telephoto lenses.
diff --git a/camera/camerax/references/camera1-to-camerax.md b/camera/camerax/references/camera1-to-camerax.md
index 9c6e80e..03bfee5 100644
--- a/camera/camerax/references/camera1-to-camerax.md
+++ b/camera/camerax/references/camera1-to-camerax.md
@@ -7,9 +7,9 @@
## Initialize `ProcessCameraProvider`
-Request the `ProcessCameraProvider` and bind use cases to the Activity or
-Fragment lifecycle.
+Request the `ProcessCameraProvider` and bind use cases to the Activity or Fragment lifecycle.
+
```kotlin
val context = LocalContext.current
@@ -36,6 +36,7 @@ LaunchedEffect(context, lifecycleOwner) {
)
val cameraControl = camera.cameraControl
}
+
```
@@ -50,21 +51,25 @@ Use `androidx.camera.view.PreviewView`.
1. **Set up preview**:
+
```kotlin
preview.setSurfaceProvider(previewView.surfaceProvider)
+
```
2. **Handle tap-to-focus**:
+
```kotlin
val factory = previewView.meteringPointFactory
val point = factory.createPoint(x, y) // x, y from touch event
val action = FocusMeteringAction.Builder(point, FocusMeteringAction.FLAG_AF).build()
cameraControl?.startFocusAndMetering(action)
+
```
@@ -75,6 +80,7 @@ Use `androidx.camera.compose.CameraXViewfinder`.
1. **Set up preview and SurfaceRequest**:
+
```kotlin
var surfaceRequest by remember { mutableStateOf(null) }
@@ -83,12 +89,14 @@ Use `androidx.camera.compose.CameraXViewfinder`.
setSurfaceProvider { request -> surfaceRequest = request }
}
}
+
```
2. **Render viewfinder**:
+
```kotlin
surfaceRequest?.let { request ->
@@ -98,12 +106,14 @@ Use `androidx.camera.compose.CameraXViewfinder`.
modifier = Modifier
)
}
+
```
3. **Handle tap-to-focus in Compose**:
+
```kotlin
// Inside your tap gesture handler...
@@ -115,12 +125,14 @@ Use `androidx.camera.compose.CameraXViewfinder`.
val point = factory.createPoint(surfaceCoords.x, surfaceCoords.y)
val action = FocusMeteringAction.Builder(point, FocusMeteringAction.FLAG_AF).build()
cameraControl?.startFocusAndMetering(action)
+
```
4. **Update target rotation for Compose**:
+
```kotlin
LaunchedEffect(configuration) {
@@ -130,15 +142,16 @@ Use `androidx.camera.compose.CameraXViewfinder`.
preview.targetRotation = rotation
}
}
+
```
## Capture a photo
-Use the `ImageCapture` use case to take the picture. The `ImageProxy` handles
-rotation directly.
+Use the `ImageCapture` use case to take the picture. The `ImageProxy` handles rotation directly.
+
```kotlin
imageCapture.takePicture(
@@ -170,15 +183,16 @@ imageCapture.takePicture(
}
}
)
+
```
## Switch cameras
-To flip between front and rear cameras, change the `CameraSelector` and
-retrigger the `ProcessCameraProvider` logic.
+To flip between front and rear cameras, change the `CameraSelector` and retrigger the `ProcessCameraProvider` logic.
+
```kotlin
lensFacing = if (lensFacing == CameraSelector.LENS_FACING_BACK) {
@@ -186,6 +200,7 @@ lensFacing = if (lensFacing == CameraSelector.LENS_FACING_BACK) {
} else {
CameraSelector.LENS_FACING_BACK
}
+
```
diff --git a/camera/camerax/references/camera2-to-camerax.md b/camera/camerax/references/camera2-to-camerax.md
index 5b21f87..eee1510 100644
--- a/camera/camerax/references/camera2-to-camerax.md
+++ b/camera/camerax/references/camera2-to-camerax.md
@@ -1,10 +1,6 @@
-Camera2 offers granular control but introduces boilerplate: managing
-`CameraDevice` states, `CameraCaptureSession` lifecycles, background threads,
-`HandlerThread`, and manual orientation calculations.
+Camera2 offers granular control but introduces boilerplate: managing `CameraDevice` states, `CameraCaptureSession` lifecycles, background threads, `HandlerThread`, and manual orientation calculations.
-CameraX simplifies this by binding high-level `UseCase`s such as `Preview`,
-`ImageCapture`, and `ImageAnalysis` directly to Android lifecycles, handling
-thread management and device-specific workarounds automatically.
+CameraX simplifies this by binding high-level `UseCase`s such as `Preview`, `ImageCapture`, and `ImageAnalysis` directly to Android lifecycles, handling thread management and device-specific workarounds automatically.
*** ** * ** ***
@@ -21,10 +17,9 @@ Migrating to CameraX removes manual setup code:
## Initialize `ProcessCameraProvider`
-Request the `ProcessCameraProvider` and bind your use cases to the
-`LifecycleOwner` activity or fragment. This replaces the
-`CameraManager.openCamera` flow.
+Request the `ProcessCameraProvider` and bind your use cases to the `LifecycleOwner` activity or fragment. This replaces the `CameraManager.openCamera` flow.
+
```kotlin
val context = LocalContext.current
@@ -56,6 +51,7 @@ LaunchedEffect(context, lifecycleOwner) {
imageAnalysis
)
}
+
```
@@ -64,17 +60,17 @@ LaunchedEffect(context, lifecycleOwner) {
## Implement the preview and tap-to-focus
-CameraX handles surface configuration automatically. Choose based on your UI
-toolkit:
+CameraX handles surface configuration automatically. Choose based on your UI toolkit:
### Option A: For Android Views
-Use `androidx.camera.view.PreviewView` in your layout, and bind it to the
-`Preview` use case.
+Use `androidx.camera.view.PreviewView` in your layout, and bind it to the `Preview` use case.
+
```kotlin
preview.setSurfaceProvider(previewView.surfaceProvider)
+
```
@@ -83,6 +79,7 @@ preview.setSurfaceProvider(previewView.surfaceProvider)
Use `androidx.camera.compose.CameraXViewfinder`.
+
```kotlin
var surfaceRequest by remember { mutableStateOf(null) }
@@ -91,6 +88,7 @@ val preview = remember {
setSurfaceProvider { request -> surfaceRequest = request }
}
}
+
```
@@ -99,10 +97,9 @@ val preview = remember {
## Capture a photo
-Replace `ImageReader` capture flows and
-`CaptureRequest.Builder.TEMPLATE_STILL_CAPTURE` with the `ImageCapture` use
-case. CameraX handles the rotation natively using the returned `ImageProxy`.
+Replace `ImageReader` capture flows and `CaptureRequest.Builder.TEMPLATE_STILL_CAPTURE` with the `ImageCapture` use case. CameraX handles the rotation natively using the returned `ImageProxy`.
+
```kotlin
imageCapture.takePicture(
@@ -134,6 +131,7 @@ imageCapture.takePicture(
}
}
)
+
```
@@ -142,9 +140,9 @@ imageCapture.takePicture(
## Implement image analysis
-If you were using `ImageReader` in Camera2 to access raw frames, e.g., for QR
-scanning or ML,, replace it with the CameraX `ImageAnalysis` use case.
+If you were using `ImageReader` in Camera2 to access raw frames, e.g., for QR scanning or ML,, replace it with the CameraX `ImageAnalysis` use case.
+
```kotlin
imageAnalysis.setAnalyzer(cameraExecutor) { imageProxy ->
@@ -157,6 +155,7 @@ imageAnalysis.setAnalyzer(cameraExecutor) { imageProxy ->
imageProxy.close()
}
}
+
```
@@ -165,10 +164,9 @@ imageAnalysis.setAnalyzer(cameraExecutor) { imageProxy ->
## Use Camera2 interop
-If your app requires specific Camera2 configuration options, such as custom
-exposure modes or flash settings, that aren't exposed directly in CameraX,
-use `Camera2Interop` to apply them to your CameraX use cases.
+If your app requires specific Camera2 configuration options, such as custom exposure modes or flash settings, that aren't exposed directly in CameraX, use `Camera2Interop` to apply them to your CameraX use cases.
+
```kotlin
// Use Camera2Interop to set Camera2-specific capture options
@@ -180,6 +178,7 @@ extender.setCaptureRequestOption(
CaptureRequest.FLASH_MODE,
CaptureRequest.FLASH_MODE_TORCH
)
+
```
diff --git a/camera/camerax/references/expert-blueprints.md b/camera/camerax/references/expert-blueprints.md
index e1f2f25..753347b 100644
--- a/camera/camerax/references/expert-blueprints.md
+++ b/camera/camerax/references/expert-blueprints.md
@@ -1,6 +1,4 @@
-Complex camera features often fail due to "Agent Stall" or timeouts when
-attempted in a single turn. Use these blueprints to break tasks into manageable
-phases.
+Complex camera features often fail due to "Agent Stall" or timeouts when attempted in a single turn. Use these blueprints to break tasks into manageable phases.
## Manual controls
@@ -54,5 +52,4 @@ phases.
## Low-light capture
-For guidance on Night Mode Extensions and Low Light Boost,
-[low-light.md](https://developer.android.com/agents/skills/camera/camerax/references/low-light).
\ No newline at end of file
+For guidance on Night Mode Extensions and Low Light Boost, [low-light.md](https://developer.android.com/agents/skills/camera/camerax/references/low-light).
\ No newline at end of file
diff --git a/camera/camerax/references/foldables.md b/camera/camerax/references/foldables.md
index 22d378a..f0dd882 100644
--- a/camera/camerax/references/foldables.md
+++ b/camera/camerax/references/foldables.md
@@ -1,6 +1,4 @@
-Foldable devices introduce unique challenges for camera applications, including
-dynamic layout changes, multiple display orientations, and physical device
-postures, such as tabletop and book modes.
+Foldable devices introduce unique challenges for camera applications, including dynamic layout changes, multiple display orientations, and physical device postures, such as tabletop and book modes.
## Manage fold states and postures
@@ -16,9 +14,9 @@ postures, such as tabletop and book modes.
### Detect posture changes
-Use the Jetpack WindowManager library to observe the device's hinge state and
-fold layout.
+Use the Jetpack WindowManager library to observe the device's hinge state and fold layout.
+
```kotlin
lifecycleScope.launch {
@@ -33,15 +31,14 @@ lifecycleScope.launch {
}
}
}
+
```
### Handle tabletop mode
-In Tabletop mode, horizontal fold, you should move the viewfinder to the top
-half of the screen and the controls to the bottom half to prevent the user from
-seeing a "bent" image.
+In Tabletop mode, horizontal fold, you should move the viewfinder to the top half of the screen and the controls to the bottom half to prevent the user from seeing a "bent" image.
- **Identify orientation:** Check `FoldingFeature.orientation`.
- **Calculate geometry:** Use `FoldingFeature.bounds` to identify the hinge's physical location on the screen.
@@ -49,9 +46,9 @@ seeing a "bent" image.
### Coordinate mapping and `Viewport`
-When the UI layout changes due to a fold, you **must** update the `Viewport` to
-ensure that tap-to-focus and image capture coordinates remain accurate.
+When the UI layout changes due to a fold, you **must** update the `Viewport` to ensure that tap-to-focus and image capture coordinates remain accurate.
+
```kotlin
val viewport = ViewPort.Builder(Rational(viewfinder.width, viewfinder.height), display.rotation)
@@ -62,14 +59,14 @@ val useCaseGroup = UseCaseGroup.Builder()
.addUseCase(preview)
.setViewPort(viewport)
.build()
+
```
### Rear display mode
-Some foldables allow using the rear camera with the cover display while the
-device is unfolded.
+Some foldables allow using the rear camera with the cover display while the device is unfolded.
- **Verification:** If available through OEM SDKs or Android 14 (API level 34) or higher, check `DeviceState.REAR_DISPLAY_STATE`.
- **Logic:** Handle preview detachment and reattachment on different display surfaces with varying aspect ratios.
diff --git a/camera/camerax/references/immutability.md b/camera/camerax/references/immutability.md
index 1dade21..30e11f6 100644
--- a/camera/camerax/references/immutability.md
+++ b/camera/camerax/references/immutability.md
@@ -1,11 +1,8 @@
-Many Android APIs are designed with immutability in mind to prevent race
-conditions in async environments. However, this often trips up developers used
-to mutable builder patterns.
+Many Android APIs are designed with immutability in mind to prevent race conditions in async environments. However, this often trips up developers used to mutable builder patterns.
## Common immutable classes
-The following classes use fluent APIs that **return a new instance**. You must
-reassign the variable.
+The following classes use fluent APIs that **return a new instance**. You must reassign the variable.
| Class | Methods that return a new instance | Result if not reassigned |
|---|---|---|
@@ -20,6 +17,7 @@ reassign the variable.
To set up video recording, use the following code:
+
```kotlin
// WRONG
@@ -42,6 +40,7 @@ run {
pending = pending.withAudioEnabled() // Reassignment
val active = pending.start(exec, listener)
}
+
```
@@ -50,11 +49,13 @@ run {
To set up the viewport, use the following code:
+
```kotlin
val viewport = ViewPort.Builder(Rational(width, height), displayRotation)
.setScaleType(ViewPort.FILL_CENTER)
.build()
+
```
\ No newline at end of file
diff --git a/camera/camerax/references/low-light.md b/camera/camerax/references/low-light.md
index e03e00c..3650fa5 100644
--- a/camera/camerax/references/low-light.md
+++ b/camera/camerax/references/low-light.md
@@ -1,5 +1,4 @@
-This guide covers implementing low-light features using **Night mode
-extensions** and **Low Light Boost (LLB)**.
+This guide covers implementing low-light features using **Night mode extensions** and **Low Light Boost (LLB)**.
## Choosing the right tool
@@ -13,13 +12,13 @@ extensions** and **Low Light Boost (LLB)**.
## Night mode extension
-CameraX Extensions provide access to the device's built-in computational
-photography pipeline.
+CameraX Extensions provide access to the device's built-in computational photography pipeline.
### Basic setup
To set up the extension, initialize the extension manager:
+
```kotlin
// Use ListenableFuture.await() extension function for coroutine support
@@ -30,6 +29,7 @@ if (extensionsManager.isExtensionAvailable(cameraSelector, ExtensionMode.NIGHT))
)
cameraProvider.bindToLifecycle(lifecycleOwner, nightSelector, imageCapture, preview)
}
+
```
@@ -42,6 +42,7 @@ if (extensionsManager.isExtensionAvailable(cameraSelector, ExtensionMode.NIGHT))
val imageCapture = ImageCapture.Builder()
.setPostviewEnabled(true)
.build()
+
```
- **Extension strength** : Let users control the intensity of the night effect.
@@ -50,6 +51,7 @@ if (extensionsManager.isExtensionAvailable(cameraSelector, ExtensionMode.NIGHT))
val extensionsManager = ExtensionsManager.getInstanceAsync(context, cameraProvider).await()
val extensionsControl = extensionsManager.getCameraExtensionsControl(camera.cameraControl)
extensionsControl?.setExtensionStrength(strength)
+
```
- **Capture progress** : Show a UI progress bar for long exposures.
@@ -61,6 +63,7 @@ if (extensionsManager.isExtensionAvailable(cameraSelector, ExtensionMode.NIGHT))
} catch (e: ImageCaptureException) {
// Handle capture failure
}
+
```
*** ** * ** ***
@@ -71,8 +74,7 @@ LLB is designed for preview and video streams where you prefer high frame rates.
### AE mode
-The built-in CameraX way to prioritize brightness. It modifies the hardware's
-auto-exposure algorithm.
+The built-in CameraX way to prioritize brightness. It modifies the hardware's auto-exposure algorithm.
- **Activation** : Use `CameraControl.enableLowLightBoostAsync`.
- **Implementation** :
@@ -80,6 +82,7 @@ auto-exposure algorithm.
```kotlin
// Enable Low Light Boost (LLB) natively in CameraX 1.4+
camera.cameraControl.enableLowLightBoostAsync(true)
+
```
- **Monitoring** : Observe `CameraInfo.lowLightBoostState` to track when the hardware actively applies the enhancement.
@@ -112,6 +115,7 @@ To implement Google Play services LLB, follow these core steps:
.addUseCase(videoCapture)
.addEffect(effect)
.build()
+
```
4. **Scene detection** : Use `session.setSceneDetectorCallback` to receive `boostStrength` updates for real-time UI indicators.
diff --git a/camera/camerax/references/mlkit-spatial.md b/camera/camerax/references/mlkit-spatial.md
index 833daf1..0b29bb2 100644
--- a/camera/camerax/references/mlkit-spatial.md
+++ b/camera/camerax/references/mlkit-spatial.md
@@ -1,6 +1,4 @@
-When you use ML Kit for features such as face mesh, object detection, or pose
-detection, the most common failure point is the coordinate disparity between the
-analysis image and the viewfinder UI.
+When you use ML Kit for features such as face mesh, object detection, or pose detection, the most common failure point is the coordinate disparity between the analysis image and the viewfinder UI.
## The mapping mindset
@@ -16,25 +14,23 @@ analysis image and the viewfinder UI.
### Coordinate transformation matrix
-Android provides the `Viewport` and `UseCaseGroup` APIs to calculate the
-transformation matrix automatically. **Don't** calculate aspect ratio scaling
-manually.
+Android provides the `Viewport` and `UseCaseGroup` APIs to calculate the transformation matrix automatically. **Don't** calculate aspect ratio scaling manually.
+
```kotlin
val transform = previewView.viewPort?.let { viewPort ->
// Use CameraX's built-in coordinate mapper
viewPort.getTransformationMatrix(imageProxy.imageInfo.rotationDegrees)
}
+
```
### Handling the "double rotation" bug
-ML Kit results, bounding boxes, are relative to the **rotated buffer**. If the
-device is in portrait, the buffer is often 480x640, landscape, but the screen
-is 1080x1920.
+ML Kit results, bounding boxes, are relative to the **rotated buffer**. If the device is in portrait, the buffer is often 480x640, landscape, but the screen is 1080x1920.
To map the coordinates, use the following workflow:
@@ -44,20 +40,20 @@ To map the coordinates, use the following workflow:
### Face mesh and pose normalization
-For high-precision spatial analysis, for example, "Is the user's hand at a
-specific screen button?", use **normalized coordinates from 0.0 to 1.0**.
+For high-precision spatial analysis, for example, "Is the user's hand at a specific screen button?", use **normalized coordinates from 0.0 to 1.0**.
+
```kotlin
// Example: Converting a Pose landmark to a Screen Coordinate
val screenX = landmark.position.x / analysisWidth * screenWidth
val screenY = landmark.position.y / analysisHeight * screenHeight
+
```
-**Warning** : Always account for **mirrored lenses** . If the `LENS_FACING_FRONT`
-is used, you must flip the X-coordinate: `actualX = screenWidth - screenX`.
+**Warning** : Always account for **mirrored lenses** . If the `LENS_FACING_FRONT` is used, you must flip the X-coordinate: `actualX = screenWidth - screenX`.
### Overlays and canvas clipping
diff --git a/camera/camerax/references/modern-apis.md b/camera/camerax/references/modern-apis.md
index 616d549..32f0d56 100644
--- a/camera/camerax/references/modern-apis.md
+++ b/camera/camerax/references/modern-apis.md
@@ -1,5 +1,4 @@
-Always prefer these various abstractions over legacy Camera2 or early CameraX
-implementations.
+Always prefer these various abstractions over legacy Camera2 or early CameraX implementations.
## Compare APIs
@@ -38,5 +37,4 @@ Add the following dependencies to your `libs.versions.toml` file:
androidx-camera-extensions = { group = "androidx.camera", name =
"camera-extensions", version.ref = "camerax" }
-Refer to the official [CameraX Release Notes](https://developer.android.com/jetpack/androidx/releases/camera) for the
-stable versions.
\ No newline at end of file
+Refer to the official [CameraX Release Notes](https://developer.android.com/jetpack/androidx/releases/camera) for the stable versions.
\ No newline at end of file
diff --git a/camera/camerax/references/testing.md b/camera/camerax/references/testing.md
index 972f285..2c24bc3 100644
--- a/camera/camerax/references/testing.md
+++ b/camera/camerax/references/testing.md
@@ -1,6 +1,4 @@
-Automated testing for camera features is notoriously difficult because you
-can't easily mock physical hardware, lighting, or motion. This guide provides
-patterns for reliable, hermetic camera tests.
+Automated testing for camera features is notoriously difficult because you can't easily mock physical hardware, lighting, or motion. This guide provides patterns for reliable, hermetic camera tests.
## Develop a testing mindset
@@ -17,42 +15,41 @@ patterns for reliable, hermetic camera tests.
### Fakes over mocks
-**Don't use Mockito.** Relying on mocks for complex, rapidly changing interfaces
-like `ImageProxy` or `CameraInfo` makes tests brittle. Instead, build "Fake"
-implementations that verify state rather than behavior.
+**Don't use Mockito.** Relying on mocks for complex, rapidly changing interfaces like `ImageProxy` or `CameraInfo` makes tests brittle. Instead, build "Fake" implementations that verify state rather than behavior.
+
```kotlin
// Create a Fake ImageProxy for ML Testing (Fakes over Mocks)
val fakeImage = FakeImageProxy(w = 640, h = 480)
// Feed the fake buffer into your analyzer
+
```
### Mock camera capabilities
-Use `FakeAppConfig` from `androidx.camera:camera-testing` to simulate specific
-hardware constraints in tests, such as a device without a flash.
+Use `FakeAppConfig` from `androidx.camera:camera-testing` to simulate specific hardware constraints in tests, such as a device without a flash.
+
```kotlin
// Use awaitInstance() extension function for coroutine-based provider retrieval
val cameraProvider = ProcessCameraProvider.awaitInstance(context)
+
```
### Use Truth assertions
-Use Google Truth, `assertThat`, instead of standard JUnit assertions. It
-provides more readable assertion chains and useful failure messages.
+Use Google Truth, `assertThat`, instead of standard JUnit assertions. It provides more readable assertion chains and useful failure messages.
### Test asynchronous lifecycles
-Camera initialization is asynchronous. Use `IdlingResource` to ensure
-your test waits for the `UseCase` to be bound before asserting.
+Camera initialization is asynchronous. Use `IdlingResource` to ensure your test waits for the `UseCase` to be bound before asserting.
To test asynchronous lifecycles, use the following pattern:
diff --git a/camera/camerax/references/thermals.md b/camera/camerax/references/thermals.md
index 41cfe19..0447f27 100644
--- a/camera/camerax/references/thermals.md
+++ b/camera/camerax/references/thermals.md
@@ -1,6 +1,4 @@
-Camera operations are among the most power-intensive tasks on mobile devices.
-Without proactive management, the system throttle hardware, drop frames, or
-force-close the camera app.
+Camera operations are among the most power-intensive tasks on mobile devices. Without proactive management, the system throttle hardware, drop frames, or force-close the camera app.
## The thermal management strategy
@@ -16,9 +14,9 @@ force-close the camera app.
### Stream use case optimization
-Android 13 (API level 33) introduced `StreamUseCase`. This is the **single most
-effective** way to tell the hardware how to balance quality versus power.
+Android 13 (API level 33) introduced `StreamUseCase`. This is the **single most effective** way to tell the hardware how to balance quality versus power.
+
```kotlin
// In CameraX: Set the hint on your Use Case
@@ -30,6 +28,7 @@ val preview = Preview.Builder()
)
}
.build()
+
```
@@ -43,9 +42,9 @@ Review the following key use cases for stream optimization:
### Monitor thermal status
-Don't wait for a crash. Monitor the `PowerManager` status and react before
-`THERMAL_STATUS_CRITICAL`.
+Don't wait for a crash. Monitor the `PowerManager` status and react before `THERMAL_STATUS_CRITICAL`.
+
```kotlin
val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
@@ -63,6 +62,7 @@ powerManager.addThermalStatusListener { status ->
}
}
}
+
```
diff --git a/camera/camerax/references/wear-os.md b/camera/camerax/references/wear-os.md
index 4a942db..11ae45f 100644
--- a/camera/camerax/references/wear-os.md
+++ b/camera/camerax/references/wear-os.md
@@ -1,6 +1,4 @@
-Developing camera features for Wear OS is rarely about the watch's own lens, if
-it even has one. It's almost always about creating a **Remote Viewfinder** to
-control the phone's camera.
+Developing camera features for Wear OS is rarely about the watch's own lens, if it even has one. It's almost always about creating a **Remote Viewfinder** to control the phone's camera.
## The Wear OS remote mindset
@@ -17,8 +15,7 @@ control the phone's camera.
### The circular UI challenge
-Wear OS devices are often round. Standard rectangular layouts clip corner
-buttons.
+Wear OS devices are often round. Standard rectangular layouts clip corner buttons.
Follow these blueprint recommendations:
@@ -30,6 +27,7 @@ Follow these blueprint recommendations:
You can't send a raw 60 fps stream over Bluetooth. compress and throttle.
+
```kotlin
// Example: Sending a viewfinder frame to the watch
@@ -41,30 +39,31 @@ if (bitmap != null) {
}
Wearable.getDataClient(context).putDataItem(request.asPutDataRequest())
}
+
+
```
-**Optimization** : Cap the watch preview at **10-15 fps** to preserve battery and
-bandwidth.
+**Optimization** : Cap the watch preview at **10-15 fps** to preserve battery and bandwidth.
### Remote triggers and syncing
-Use the `MessageClient` for low-latency commands like "Take Photo" or "Switch
-Camera."
+Use the `MessageClient` for low-latency commands like "Take Photo" or "Switch Camera."
+
```kotlin
// Watch sends a trigger to the phone
Wearable.getMessageClient(context).sendMessage(nodeId, "/camera/capture", null)
+
```
### Rotary input support
-On devices that support it, use the physical crown, Rotary Input, to control
-**Zoom** or **Exposure**.
+On devices that support it, use the physical crown, Rotary Input, to control **Zoom** or **Exposure**.
*** ** * ** ***
diff --git a/camera/camerax/references/xr.md b/camera/camerax/references/xr.md
index 59fae32..1edfddf 100644
--- a/camera/camerax/references/xr.md
+++ b/camera/camerax/references/xr.md
@@ -1,5 +1,4 @@
-Developing camera features for XR devices, headsets, and AR glasses requires a
-shift from 2D pixel-pushing to 3D spatial awareness.
+Developing camera features for XR devices, headsets, and AR glasses requires a shift from 2D pixel-pushing to 3D spatial awareness.
## Understand the XR development mindset
@@ -15,8 +14,7 @@ shift from 2D pixel-pushing to 3D spatial awareness.
### API selection
-On XR devices, standard `CameraX` implementations are often restricted or
-insufficient. Always use spatial software development kits (SDKs):
+On XR devices, standard `CameraX` implementations are often restricted or insufficient. Always use spatial software development kits (SDKs):
- **ARCore**: Use ARCore for plane detection, depth sensing, and motion tracking.
- **OpenXR**: Use OpenXR as the cross-platform standard for VR and AR rendering and input.
@@ -26,13 +24,13 @@ insufficient. Always use spatial software development kits (SDKs):
Unlike a 2D viewport, XR passthrough is often system-managed.
-**\[Key requirement\] Frame synchronization**: Synchronize your application's
-frame clock with the headset's head-mounted display (HMD) pose.
+**\[Key requirement\] Frame synchronization**: Synchronize your application's frame clock with the headset's head-mounted display (HMD) pose.
```kotlin
// Example: Querying the spatial pose for the current camera frame
val headPose = xrSession.getHeadPose(frameTime)
val projectionMatrix = headPose.getProjectionMatrix(eyeIndex)
+
```
diff --git a/device-ai/appfunctions/SKILL.md b/device-ai/appfunctions/SKILL.md
index ad75915..5ad96e6 100644
--- a/device-ai/appfunctions/SKILL.md
+++ b/device-ai/appfunctions/SKILL.md
@@ -9,7 +9,7 @@ description: Analyzes Android apps to identify key user workflows for AppFunctio
license: Complete terms in LICENSE.txt
metadata:
author: Google LLC
- last-updated: '2026-07-28'
+ last-updated: '2026-08-06'
keywords:
- AppFunctions
- Kotlin
@@ -20,29 +20,19 @@ metadata:
- MCP
---
-Analyzes Android apps to identify key user workflows for AppFunctions such as
-creating a note, playing media, or sending an automated or AI agent triggered
-message, voice commands, or system shortcuts, without needing to open the app
-UI.
+Analyzes Android apps to identify key user workflows for AppFunctions such as creating a note, playing media, or sending an automated or AI agent triggered message, voice commands, or system shortcuts, without needing to open the app UI.
-Generates Kotlin code to expose these workflows to the Android system,
-allowing agents to discover and execute them on-device.
+Generates Kotlin code to expose these workflows to the Android system, allowing agents to discover and execute them on-device.
-Also refines KDoc documentation to ensure AI agents correctly
-understand and use the provided functionality.
+Also refines KDoc documentation to ensure AI agents correctly understand and use the provided functionality.
## Prerequisites
-The app must **`targetSdk 36`** or newer and use **`compileSdk 37`** or newer as
-AppFunctions, part of the Android platform API, are available from Android 16
-onwards.
-Always use the Jetpack library because it handles backward compatibility.
+The app must **`targetSdk 36`** or newer and use **`compileSdk 37`** or newer as AppFunctions, part of the Android platform API, are available from Android 16 onwards. Always use the Jetpack library because it handles backward compatibility.
## Workflows
-This skill enables the caller to discover features that will be provided to
-system agents, implement these with AppFunctions, improve function description
-for agents, and use ADB commands for local evaluation and testing.
+This skill enables the caller to discover features that will be provided to system agents, implement these with AppFunctions, improve function description for agents, and use ADB commands for local evaluation and testing.
The full AppFunction development flow consists of these four steps:
@@ -55,7 +45,7 @@ If users request a subset of steps, you must encourage them to use all steps.
If they apply, you must load the following references:
-- *[Context and terminology](context.md)*: Defines the ubiquitous language, architecture definitions, and design patterns across the AppFunctions skill suite. Load when you need to understand core architecture terminology or check the distinctions between modern and legacy AppFunctions APIs.
+- *[Context and terminology](references/context.md)*: Defines the ubiquitous language, architecture definitions, and design patterns across the AppFunctions skill suite. Load when you need to understand core architecture terminology or check the distinctions between modern and legacy AppFunctions APIs.
- *[Migration to service entry point](references/migrate-to-service-entry-point.md)* : Documents the systematic procedure for migrating Android applications using AppFunctions versions 1.0.0-alpha09 and lower to `AppFunctionServiceEntryPoint` architecture introduced in version 1.0.0-alpha10. Load when a user asks to migrate or upgrade existing AppFunctions code, or when you encounter legacy `AppFunctionConfiguration.Provider` implementations.
## Critical constraints
@@ -67,5 +57,5 @@ If they apply, you must load the following references:
- If you encounter build-time errors such as Kotlin Symbol Processing (KSP) issues, see [Implementation and configuration](references/implementation-configuration.md).
- If you encounter runtime errors such as missing services or execution failures, see [Testing and debugging](references/adb-interaction-testing.md).
-- If you need architecture definitions and vocabulary, see [Context and terminology](context.md).
+- If you need architecture definitions and vocabulary, see [Context and terminology](references/context.md).
- If you encounter issues when upgrading legacy configurations, see [Migration to service entry point](references/migrate-to-service-entry-point.md).
diff --git a/device-ai/appfunctions/context.md b/device-ai/appfunctions/context.md
deleted file mode 100644
index dc49d25..0000000
--- a/device-ai/appfunctions/context.md
+++ /dev/null
@@ -1,26 +0,0 @@
-Defines the ubiquitous language for the Android AppFunctions skill suite.
-
-## Architecture and versioning
-
-`AppFunctionServiceEntryPoint` API:
-This compile-time AppFunctions architecture was introduced in version
-1.0.0-alpha10. You annotate a wrapper service extending
-`AppFunctionService` with `@AppFunctionServiceEntryPoint`. KSP then generates
-XML metadata and routes services at compile time.
-
-Legacy manual provider API:
-This deprecated AppFunctions architecture applies to version
-1.0.0-alpha09 and earlier. Applications implement
-`AppFunctionConfiguration.Provider` on the `Application` class. Methods
-require `AppFunctionContext` as the first parameter. Projects depend on
-a standalone `appfunctions-service` library.
-
-## Patterns
-
-Service entry point pattern:
-Version 1.0.0-alpha10 introduced this architectural pattern. You
-declare `@AppFunction` methods directly inside an abstract class extending
-`AppFunctionService`. This class uses `@AppFunctionServiceEntryPoint` and
-`@AndroidEntryPoint` annotations. These annotations let you inject data
-sources or repositories directly, without an intermediate business logic
-delegation layer.
\ No newline at end of file
diff --git a/device-ai/appfunctions/references/adb-interaction-testing.md b/device-ai/appfunctions/references/adb-interaction-testing.md
index b487923..b7fac4a 100644
--- a/device-ai/appfunctions/references/adb-interaction-testing.md
+++ b/device-ai/appfunctions/references/adb-interaction-testing.md
@@ -1,16 +1,13 @@
-Provides commands to interact with AppFunctions on a connected device or
-emulator using ADB for AppFunction testing and debugging.
+Provides commands to interact with AppFunctions on a connected device or emulator using ADB for AppFunction testing and debugging.
## Instructions
### Scenario 1: List app functions
-Use this scenario when you want to see which app functions are registered on
-the device.
+Use this scenario when you want to see which app functions are registered on the device.
1. **List all functions** : To view all registered app functions in JSON format, run `adb shell cmd app_function list-app-functions`.
-2. **Filter by package** : To view functions for a specific package, pipe the output to `grep` or a JSON tool: `adb shell cmd app_function
- list-app-functions | grep `.
+2. **Filter by package** : To view functions for a specific package, pipe the output to `grep` or a JSON tool: `adb shell cmd app_function list-app-functions | grep `.
### Scenario 2: Invoke app functions
@@ -19,38 +16,28 @@ If you want to test the execution of an app function, use this scenario.
1. **Analyze description** : Before invoking, you must read the `description` field for the function in the `list-app-functions` output. This often contains critical usage constraints, required workflows, or disambiguation rules.
2. **Follow constraints**: Follow all instructions in the description, such as asking the user to disambiguate or calling another tool first.
3. **Format parameters** : Format the `--parameters` argument as a valid JSON string that represents the function's input arguments.
-4. **Execute function** : Use `adb shell cmd app_function execute-app-function
- --package --function
- --parameters ''`.
+4. **Execute function** : Use `adb shell cmd app_function execute-app-function --package --function --parameters ''`.
5. **Handle response** : The command returns the result as a JSON string. To get brief YAML output, use `--brief-yaml`.
### Scenario 3: Manage function state
If you need to enable or disable an app function for testing, use this scenario.
-1. **Set enabled state** : Use `adb shell cmd app_function set-enabled
- --package
- --function
- --state `.
+1. **Set enabled state** : Use `adb shell cmd app_function set-enabled --package --function --state `.
## Critical constraints
### Follow metadata descriptions
-**Mandatory** : The `description` field in the app function metadata is a set of
-instructions for the LLM. If a description says to "disambiguate with the user"
-or "call another function first," you must perform those steps before execution.
+**Mandatory** : The `description` field in the app function metadata is a set of instructions for the LLM. If a description says to "disambiguate with the user" or "call another function first," you must perform those steps before execution.
### JSON escaping
-**Critical** : When passing JSON using `adb shell`, always wrap the JSON string
-in single quotes to prevent the shell from interpreting special characters or
-spaces. Example: `--parameters '{"key": "value"}'`.
+**Critical** : When passing JSON using `adb shell`, always wrap the JSON string in single quotes to prevent the shell from interpreting special characters or spaces. Example: `--parameters '{"key": "value"}'`.
### Device availability
-The `app_function` service must be available on the device. If `cmd: Can't find
-service: app_function` is returned, the device doesn't support this feature.
+The `app_function` service must be available on the device. If `cmd: Can't find service: app_function` is returned, the device doesn't support this feature.
## Examples
@@ -58,8 +45,7 @@ service: app_function` is returned, the device doesn't support this feature.
adb shell cmd app_function help
-If executing the preceding command returns a help page, use the commands and
-parameters provided to guide the ADB interaction testing tool interactions.
+If executing the preceding command returns a help page, use the commands and parameters provided to guide the ADB interaction testing tool interactions.
### Example 2: List all registered app functions
@@ -91,5 +77,4 @@ parameters provided to guide the ADB interaction testing tool interactions.
**Cause**: The function ID or package name is incorrect.
-**Solution** : Run `list-app-functions` and search for the relevant identifiers
-in the JSON output.
\ No newline at end of file
+**Solution** : Run `list-app-functions` and search for the relevant identifiers in the JSON output.
\ No newline at end of file
diff --git a/device-ai/appfunctions/references/context.md b/device-ai/appfunctions/references/context.md
new file mode 100644
index 0000000..9d18e2c
--- /dev/null
+++ b/device-ai/appfunctions/references/context.md
@@ -0,0 +1,11 @@
+Defines the ubiquitous language for the Android AppFunctions skill suite.
+
+## Architecture and versioning
+
+`AppFunctionServiceEntryPoint` API: This compile-time AppFunctions architecture was introduced in version 1.0.0-alpha10. You annotate a wrapper service extending `AppFunctionService` with `@AppFunctionServiceEntryPoint`. KSP then generates XML metadata and routes services at compile time.
+
+Legacy manual provider API: This deprecated AppFunctions architecture applies to version 1.0.0-alpha09 and earlier. Applications implement `AppFunctionConfiguration.Provider` on the `Application` class. Methods require `AppFunctionContext` as the first parameter. Projects depend on a standalone `appfunctions-service` library.
+
+## Patterns
+
+Service entry point pattern: Version 1.0.0-alpha10 introduced this architectural pattern. You declare `@AppFunction` methods directly inside an abstract class extending `AppFunctionService`. This class uses `@AppFunctionServiceEntryPoint` and `@AndroidEntryPoint` annotations. These annotations let you inject data sources or repositories directly, without an intermediate business logic delegation layer.
\ No newline at end of file
diff --git a/device-ai/appfunctions/references/feature-discovery-analysis.md b/device-ai/appfunctions/references/feature-discovery-analysis.md
index 583f67c..4adb255 100644
--- a/device-ai/appfunctions/references/feature-discovery-analysis.md
+++ b/device-ai/appfunctions/references/feature-discovery-analysis.md
@@ -13,15 +13,11 @@ Analyzes Android codebases to identify and recommend high-value AppFunctions.
### Tool-first thinking
-Avoid recommending functions that are purely informational or redundant with
-existing system actions. Focus on "mutations" (writing data) or "rich queries"
-(finding specific entities).
+Avoid recommending functions that are purely informational or redundant with existing system actions. Focus on "mutations" (writing data) or "rich queries" (finding specific entities).
### Security and privacy
-Don't recommend exposing functions that handle raw credentials, financial
-secrets, or irreversible destructive actions without explicit user confirmation
-steps.
+Don't recommend exposing functions that handle raw credentials, financial secrets, or irreversible destructive actions without explicit user confirmation steps.
## Examples
@@ -29,9 +25,7 @@ steps.
**Recommended AppFunction** : `playArtistRadio`
-**Rationale**: Lets you start a personalized music stream using a voice
-command, bypassing several layers of navigation in the "Search" and "Artist"
-menus.
+**Rationale**: Lets you start a personalized music stream using a voice command, bypassing several layers of navigation in the "Search" and "Artist" menus.
**Input required** : `artistName` as a `String`.
@@ -39,33 +33,22 @@ menus.
**Recommended AppFunction** : `searchContacts`
-**Rationale** : Serves as a "rich query" to resolve a human-readable contact
-name, email, or chat group to a unique identifier (`endpointValue`), which is a
-prerequisite before executing actions like sending messages or
-initiating calls. Also allows retrieving recently contacted entities when given
-a blank query.
+**Rationale** : Serves as a "rich query" to resolve a human-readable contact name, email, or chat group to a unique identifier (`endpointValue`), which is a prerequisite before executing actions like sending messages or initiating calls. Also allows retrieving recently contacted entities when given a blank query.
-**Input required** : Query as a `String`, and Filter Type as a `String`
-constrained to `"INDIVIDUAL"` or `"GROUP"`.
+**Input required** : Query as a `String`, and Filter Type as a `String` constrained to `"INDIVIDUAL"` or `"GROUP"`.
### Example 3: Chat app message sending
**Recommended AppFunction** : `send`
-**Rationale**: This mutation function lets you send text messages and
-optional image attachments to a contact or group using natural language
-commands, for example, "Tell Alice I'm running 5 minutes late." This
-eliminates multi-step UI navigation across contact lists and conversation
-threads.
+**Rationale**: This mutation function lets you send text messages and optional image attachments to a contact or group using natural language commands, for example, "Tell Alice I'm running 5 minutes late." This eliminates multi-step UI navigation across contact lists and conversation threads.
-**Input required** : Endpoint Value as a `String`, Message Body as a `String`,
-and Image URIs as an optional `List` of URIs.
+**Input required** : Endpoint Value as a `String`, Message Body as a `String`, and Image URIs as an optional `List` of URIs.
### Example 4: Chat app voice calling
**Recommended AppFunction** : `makeCall`
-**Rationale**: Lets you initiate voice calls hands-free to a contact or
-group using an AI agent without navigating the app's UI.
+**Rationale**: Lets you initiate voice calls hands-free to a contact or group using an AI agent without navigating the app's UI.
**Input required** : `endpointValue` as a `String`.
\ No newline at end of file
diff --git a/device-ai/appfunctions/references/implementation-configuration.md b/device-ai/appfunctions/references/implementation-configuration.md
index fb9292c..4f8260e 100644
--- a/device-ai/appfunctions/references/implementation-configuration.md
+++ b/device-ai/appfunctions/references/implementation-configuration.md
@@ -1,19 +1,19 @@
-Specialized instructions for generating Kotlin implementations of AppFunctions,
-handling system-wide configuration, and managing build dependencies.
+Specialized instructions for generating Kotlin implementations of AppFunctions, handling system-wide configuration, and managing build dependencies.
## Instructions
### Step 1: Configure Gradle dependencies and KSP
-Add the following to `build.gradle.kts`. App Functions requires the KSP (Kotlin
-Symbol Processing) plugin.
+Add the following to `build.gradle.kts`. App Functions requires the KSP (Kotlin Symbol Processing) plugin.
1. **Version check** : Use library version `1.0.0-alpha10` or later from maven.google.com.
+
```kotlin
implementation(libs.androidx.appfunctions)
ksp(libs.androidx.appfunctions.compiler)
+
```
@@ -24,9 +24,9 @@ ksp(libs.androidx.appfunctions.compiler)
### Step 2: Set up app metadata XML
-Describe the app's capabilities to the LLM by defining
-`res/xml/app_metadata.xml`.
+Describe the app's capabilities to the LLM by defining `res/xml/app_metadata.xml`.
+
```xml
+
```
-Register the service and reference the app metadata in `AndroidManifest.xml`
-within the `` tag:
+Register the service and reference the app metadata in `AndroidManifest.xml` within the `` tag:
+
```xml
` tag:
+
```
@@ -96,16 +98,13 @@ When generating Kotlin code for AppFunctions, you MUST adhere to these rules:
### Step 4: Set up dependency injection and service entry points
-In version 1.0.0-alpha10 and later, App Functions use the compile-time
-`@AppFunctionServiceEntryPoint` architecture. Create an abstract class extending
-`AppFunctionService` annotated with `@AppFunctionServiceEntryPoint`. KSP
-generates the concrete service class and XML schema.
+In version 1.0.0-alpha10 and later, App Functions use the compile-time `@AppFunctionServiceEntryPoint` architecture. Create an abstract class extending `AppFunctionService` annotated with `@AppFunctionServiceEntryPoint`. KSP generates the concrete service class and XML schema.
#### Recommended approach with Hilt
-Annotate your service with `@AndroidEntryPoint` and inject your data
-repositories or use cases using standard `@Inject internal lateinit var`:
+Annotate your service with `@AndroidEntryPoint` and inject your data repositories or use cases using standard `@Inject internal lateinit var`:
+
```kotlin
@RequiresApi(36)
@@ -126,19 +125,16 @@ abstract class BaseAppFunctionServiceHeader : AppFunctionService() {
return messageRepository.send(name, endpointValue, messageBody)
}
}
+
```
#### Framework-agnostic approach with alternative dependency injection or service locators
-While Hilt is recommended, many Android applications implement AppFunctions with
-alternative dependency injection frameworks (like Koin, Anvil, or manual Service
-Locators). Because `AppFunctionService` inherits from Android
-`android.app.Service` (and therefore `Context`), you are able access your
-application's DI container directly through `applicationContext` in property
-getters or during service lifecycle execution:
+While Hilt is recommended, many Android applications implement AppFunctions with alternative dependency injection frameworks (like Koin, Anvil, or manual Service Locators). Because `AppFunctionService` inherits from Android `android.app.Service` (and therefore `Context`), you are able access your application's DI container directly through `applicationContext` in property getters or during service lifecycle execution:
+
```kotlin
@RequiresApi(36)
@@ -163,16 +159,14 @@ abstract class BaseAppFunctionServiceLocator : AppFunctionService() {
return messageRepository.send(name, endpointValue, messageBody)
}
}
+
```
### Step 5: Architectural cleanliness
-Don't attempt to make an `AppFunction` class or method OS-agnostic---App Functions are inherently part of the Android platform integration in `androidx.appfunctions`. For architectural cleanliness, use existing
-application functionality (such as existing repositories, use cases, or domain
-orchestrators) to execute the behavior within your `@AppFunction` methods rather
-than creating redundant abstraction layers around the OS service.
+Don't attempt to make an `AppFunction` class or method OS-agnostic---App Functions are inherently part of the Android platform integration in `androidx.appfunctions`. For architectural cleanliness, use existing application functionality (such as existing repositories, use cases, or domain orchestrators) to execute the behavior within your `@AppFunction` methods rather than creating redundant abstraction layers around the OS service.
@@ -180,19 +174,17 @@ than creating redundant abstraction layers around the OS service.
### KSP compliance for serializables
-**Critical constraints** : For `@AppFunctionSerializable` data classes, KSP
-only extracts documentation if it's written as inline KDoc directly for each
-property definition. Don't use class-level `@param` or `@property` tags.
+**Critical constraints** : For `@AppFunctionSerializable` data classes, KSP only extracts documentation if it's written as inline KDoc directly for each property definition. Don't use class-level `@param` or `@property` tags.
### Package integrity
-Configuration APIs and the `@AppFunction` annotation are located in
-`androidx.appfunctions`.
+Configuration APIs and the `@AppFunction` annotation are located in `androidx.appfunctions`.
## Examples
### Example: Serializable with inline KDoc
+
```kotlin
/** The parameter to create the task. */
@@ -214,6 +206,7 @@ data class Task(
/** The content of the task. */
val content: String,
)
+
```
@@ -222,6 +215,7 @@ data class Task(
### Example: Implementation detail
+
```kotlin
@RequiresApi(36)
@@ -262,6 +256,7 @@ abstract class BaseTaskAppFunctionService : AppFunctionService() {
// Maps internal TaskEntity
private fun TaskEntity.toTask() = Task(id = id, title = title, content = description)
}
+
```
diff --git a/device-ai/appfunctions/references/kdoc-refinement-optimization.md b/device-ai/appfunctions/references/kdoc-refinement-optimization.md
index c0a3209..38ce18e 100644
--- a/device-ai/appfunctions/references/kdoc-refinement-optimization.md
+++ b/device-ai/appfunctions/references/kdoc-refinement-optimization.md
@@ -5,8 +5,7 @@ Optimizes AppFunction KDoc for AI agents and Model Context Protocol.
### Workflow: Agent-centric documentation
1. **Identify the core outcome** : Start the description with a strong imperative verb, for example, "Search", "Create", or "Update". Focus on the *user benefit*, not the code implementation.
-2. **Workflow dependencies** : Explicitly state if another function must be called first using the standard phrase: **Required workflow: Call "Function
- A" first to "Objective"**.
+2. **Workflow dependencies** : Explicitly state if another function must be called first using the standard phrase: **Required workflow: Call "Function A" first to "Objective"**.
3. **Parameter documentation** :
- For **functions** : Use specific `@param` tags. Isolate validation rules and default values here.
- For **serializables** : Use inline KDoc directly for each property declaration. KSP **won't** extract documentation from class-level tags.
@@ -14,8 +13,7 @@ Optimizes AppFunction KDoc for AI agents and Model Context Protocol.
### Workflow: Global app description for server instructions
-When writing the `appfn:description` for `app_metadata.xml`, follow these
-instructions:
+When writing the `appfn:description` for `app_metadata.xml`, follow these instructions:
1. **Capture cross-function relationships**: Explain dependencies or sequences between tools, for example, "Always call 'authenticate' before fetching data.".
2. **Document operational patterns**: Guide the LLM on token-conserving usage, for example, "Use 'batch_update' over multiple 'update' calls."
@@ -29,19 +27,15 @@ instructions:
### Descriptive, not imperative
-Describe what the function *does* , not what the LLM *must* do. Avoid phrases
-like "You must call this..." in favor of "This function provides...".
+Describe what the function *does* , not what the LLM *must* do. Avoid phrases like "You must call this..." in favor of "This function provides...".
### No "fluff"
-Remove conversational padding like "This method is used to..." or "Helpful
-for...". Be concise and technical.
+Remove conversational padding like "This method is used to..." or "Helpful for...". Be concise and technical.
### Inline KDoc for serializables
-**Mandatory** : For `@AppFunctionSerializable` classes, documentation must be
-inline for each property. KSP ignores class-level `@param` or `@property` tags
-for these classes.
+**Mandatory** : For `@AppFunctionSerializable` classes, documentation must be inline for each property. KSP ignores class-level `@param` or `@property` tags for these classes.
## Examples
diff --git a/device-ai/appfunctions/references/migrate-to-service-entry-point.md b/device-ai/appfunctions/references/migrate-to-service-entry-point.md
index f350f61..a0528e9 100644
--- a/device-ai/appfunctions/references/migrate-to-service-entry-point.md
+++ b/device-ai/appfunctions/references/migrate-to-service-entry-point.md
@@ -1,7 +1,4 @@
-Follow this systematic procedure to migrate Android applications that use the
-AppFunctions API in version 1.0.0-alpha09 and lower to the compile-time
-`@AppFunctionServiceEntryPoint` architecture introduced in version
-`1.0.0-alpha10`.
+Follow this systematic procedure to migrate Android applications that use the AppFunctions API in version 1.0.0-alpha09 and lower to the compile-time `@AppFunctionServiceEntryPoint` architecture introduced in version `1.0.0-alpha10`.
*** ** * ** ***
@@ -23,9 +20,7 @@ In version `1.0.0-alpha10` featuring `@AppFunctionServiceEntryPoint`:
### Strict migration requirements from 1.0.0-alpha09 to 1.0.0-alpha10
-When focusing solely on the mandatory API changes required by the new
-`@AppFunctionServiceEntryPoint` architecture, the migration consists of four
-strict requirements that you must complete:
+When focusing solely on the mandatory API changes required by the new `@AppFunctionServiceEntryPoint` architecture, the migration consists of four strict requirements that you must complete:
1. **Build dependency consolidation** : Remove the merged `appfunctions-service` dependency while retaining core `appfunctions` and the KSP compiler.
2. **Service wrapper creation** : Replace the legacy `AppFunctionConfiguration.Provider` on the `Application` class with an abstract class extending `AppFunctionService`, annotated with `@AppFunctionServiceEntryPoint`.
@@ -38,10 +33,7 @@ strict requirements that you must complete:
### Consolidate AppFunctions build dependencies
-Remove the standalone `appfunctions-service` library from your module build
-files like `build.gradle.kts` and version catalog like `libs.versions.toml`. In
-version `1.0.0-alpha10`, all core service capabilities are consolidated directly
-within the main `appfunctions` artifact.
+Remove the standalone `appfunctions-service` library from your module build files like `build.gradle.kts` and version catalog like `libs.versions.toml`. In version `1.0.0-alpha10`, all core service capabilities are consolidated directly within the main `appfunctions` artifact.
// build.gradle.kts
dependencies {
@@ -66,16 +58,13 @@ within the main `appfunctions` artifact.
### Create a dedicated wrapper service extending `AppFunctionService`
-Instead of annotating standalone business logic classes or implementing manual
-configuration providers, create an abstract service wrapper across your project,
-for example `BaseAppFunctionService`, extending `AppFunctionService` and
-annotated with `@AppFunctionServiceEntryPoint`.
+Instead of annotating standalone business logic classes or implementing manual configuration providers, create an abstract service wrapper across your project, for example `BaseAppFunctionService`, extending `AppFunctionService` and annotated with `@AppFunctionServiceEntryPoint`.
#### Recommended approach using Hilt
-Annotate your service with `@AndroidEntryPoint` and inject your data
-repositories or use cases using standard `@Inject internal lateinit var`:
+Annotate your service with `@AndroidEntryPoint` and inject your data repositories or use cases using standard `@Inject internal lateinit var`:
+
```kotlin
@RequiresApi(36)
@@ -96,19 +85,16 @@ abstract class BaseAppFunctionService : AppFunctionService() {
return messageRepository.send(name, endpointValue, messageBody)
}
}
+
```
#### Framework-agnostic approach using alternative dependency injection or a service locator
-While Hilt is recommended, many Android applications implement AppFunctions with
-alternative dependency injection frameworks like Koin, Anvil, or manual Service
-Locators. Because `AppFunctionService` inherits from Android
-`android.app.Service` and therefore `Context`, you are able access your
-application's DI container directly through `applicationContext` in property
-getters or during service lifecycle execution:
+While Hilt is recommended, many Android applications implement AppFunctions with alternative dependency injection frameworks like Koin, Anvil, or manual Service Locators. Because `AppFunctionService` inherits from Android `android.app.Service` and therefore `Context`, you are able access your application's DI container directly through `applicationContext` in property getters or during service lifecycle execution:
+
```kotlin
@RequiresApi(36)
@@ -133,6 +119,7 @@ abstract class ServiceLocatorBaseAppFunctionService : AppFunctionService() {
return messageRepository.send(name, endpointValue, messageBody)
}
}
+
```
@@ -144,10 +131,7 @@ abstract class ServiceLocatorBaseAppFunctionService : AppFunctionService() {
### Simplify method signatures and decouple context
-Remove legacy `AppFunctionContext` parameters from your core methods. When a
-method requires an Android `Context`, for example when constructing a
-`PendingIntent`, access `this` directly from your `AppFunctionService` wrapper
-because the wrapper inherently extends `android.content.Context`.
+Remove legacy `AppFunctionContext` parameters from your core methods. When a method requires an Android `Context`, for example when constructing a `PendingIntent`, access `this` directly from your `AppFunctionService` wrapper because the wrapper inherently extends `android.content.Context`.
- suspend fun makeCall(appFunctionContext: AppFunctionContext, contactName: String?): PendingIntent
+ suspend fun makeCall(contactName: String?): PendingIntent
@@ -156,8 +140,7 @@ because the wrapper inherently extends `android.content.Context`.
### Remove legacy configuration provider
-Update your `Application` class by removing
-`AppFunctionConfiguration.Provider` and its associated builder entry points:
+Update your `Application` class by removing `AppFunctionConfiguration.Provider` and its associated builder entry points:
- abstract class BaseChatApplication : Application(), AppFunctionConfiguration.Provider { ... }
+ abstract class BaseChatApplication : Application()
@@ -166,21 +149,15 @@ Update your `Application` class by removing
### Avoid redundant abstraction layers
-Don't attempt to make an `AppFunction` class or method OS-agnostic---AppFunctions
-are inherently part of the Android platform integration through the
-`androidx.appfunctions` package. For architectural cleanliness, use existing
-application functionality, such as existing repositories, use cases, or domain
-orchestrators, to execute the behavior within your `@AppFunction` methods rather
-than creating redundant abstraction layers around the OS service.
+Don't attempt to make an `AppFunction` class or method OS-agnostic---AppFunctions are inherently part of the Android platform integration through the `androidx.appfunctions` package. For architectural cleanliness, use existing application functionality, such as existing repositories, use cases, or domain orchestrators, to execute the behavior within your `@AppFunction` methods rather than creating redundant abstraction layers around the OS service.
*** ** * ** ***
### Consolidate service and metadata manifest declarations
-Register the KSP-generated service declaration and `app_metadata` property
-inside your module manifest, for example in `src/main/AndroidManifest.xml`
-within the `` tag:
+Register the KSP-generated service declaration and `app_metadata` property inside your module manifest, for example in `src/main/AndroidManifest.xml` within the `` tag:
+
```xml
` tag:
+
```
@@ -209,18 +187,7 @@ within the `` tag:
## Verification and troubleshooting
-1. **Clean rebuild and deploy** : `bash
- ./gradlew clean installDebug`
-2. **Verify AppSearch discovery / indexing** : Run the following ADB command to
- confirm the OS successfully discovered and indexed your functions:
- `bash
- adb shell cmd app_function list-app-functions`
- *If your package doesn't appear, confirm that `android.app.appfunctions.v2`
- matches the exact asset name generated in `assets/`.*
+1. **Clean rebuild and deploy** : `bash ./gradlew clean installDebug`
+2. **Verify AppSearch discovery / indexing** : Run the following ADB command to confirm the OS successfully discovered and indexed your functions: `bash adb shell cmd app_function list-app-functions` *If your package doesn't appear, confirm that `android.app.appfunctions.v2` matches the exact asset name generated in `assets/`.*
-3. **Verify execution using ADB** :
- `bash
- adb shell "cmd app_function execute-app-function \
- --package com.example.chatapp \
- --function 'com.example.chatapp.appfunctions.BaseAppFunctionService#send' \
- --parameters '{\"name\": \"Alice\", \"endpointValue\": \"1\", \"messageBody\": \"Hello Alice!\"}'"`
\ No newline at end of file
+3. **Verify execution using ADB** : `bash adb shell "cmd app_function execute-app-function \ --package com.example.chatapp \ --function 'com.example.chatapp.appfunctions.BaseAppFunctionService#send' \ --parameters '{\"name\": \"Alice\", \"endpointValue\": \"1\", \"messageBody\": \"Hello Alice!\"}'"`
\ No newline at end of file
diff --git a/devtools/android-cli/SKILL.md b/devtools/android-cli/SKILL.md
index adb7fad..af4320b 100644
--- a/devtools/android-cli/SKILL.md
+++ b/devtools/android-cli/SKILL.md
@@ -80,30 +80,45 @@ Update the Android CLI using the `android update` command.
# `android help` output
-Usage: android [-hV] [--sdk=PARAM] [COMMAND]
+Usage: android [-hvV] [--sdk=PARAM] [COMMAND]
-h, --help Show this help message and exit.
--sdk=PARAM Path to the Android SDK
+ -v, --verbose Enable verbose output for troubleshooting
-V, --version Print version information and exit.
Commands:
- create Create a new Android project
+ create Create a new Android project from available templates. Allows
+ specifying project name, output directory, minSdk, and dry-run
+ execution.
describe Analyzes an Android project to generate descriptive metadata.
- docs Android documentation commands
- emulator Emulator commands
+ docs Android documentation commands for searching and fetching developer
+ documentation from the official knowledge base.
+ emulator Manage Android Virtual Devices (AVDs). Includes commands to start,
+ stop, list, and view details about emulators.
help Shows the help of all commands
- info Print environment information (SDK Location, etc.)
- init Initializes the environment (eg. skills) for Android CLI.
+ info Print environment information including SDK location, connected
+ devices, and configuration variables. Use specific fields to
+ narrow the output.
+ init Initializes the environment for the Android CLI. Sets up required
+ configurations, directories, and default skills.
+ install Install an Android Application (one or more APKs) to a connected
+ device or emulator without activating any components using
+ incremental optimizations for faster deployment than adb.
layout Returns the layout tree of an application
- run Deploy an Android Application
+ run Build, deploy, and launch an Android application on a connected
+ device or emulator.
screen Commands to view the device
- sdk Download and list SDK packages
- skills Manage skills
+ sdk Manage the Android SDK installation. Includes commands to install,
+ update, remove, and list available and installed SDK packages.
+ skills Manage Android CLI skills. Includes commands to install, remove,
+ list, and search for skills by keyword.
studio Android Studio commands
- update Update the Android CLI
+ update Update the Android CLI to the latest version.
create
Usage: android create [-h] [--verbose] [--list] [--minSdk=api]
--name=applicationName [-o=dest-path] [template-name]
- Create a new Android project
+ Create a new Android project from available templates. Allows specifying
+ project name, output directory, minSdk, and dry-run execution.
[template-name] The template name
-h, --help Show this help message and exit.
--minSdk=api The 'minSdk' supported by the application (default
@@ -128,15 +143,17 @@ describe
docs
Usage: android docs [-h] [COMMAND]
- Android documentation commands
+ Android documentation commands for searching and fetching developer
+ documentation from the official knowledge base.
-h, --help Show this help message and exit.
Commands:
- search Search Android documentation
- fetch Fetch Android documentation
+ search Search Android documentation. Enclose keywords in quotes.
+ fetch Fetch an Android documentation article from a URL (kb://...)
emulator
Usage: android emulator [-h] [COMMAND]
- Emulator commands
+ Manage Android Virtual Devices (AVDs). Includes commands to start, stop, list,
+ and view details about emulators.
-h, --help Show this help message and exit.
Commands:
create Creates a virtual device
@@ -153,12 +170,33 @@ help
info
Usage: android info
- Print environment information (SDK Location, etc.)
+ Print environment information including SDK location, connected devices, and
+ configuration variables. Use specific fields to narrow the output.
The specific field to print the value of. If omitted print all.
init
Usage: android init
- Initializes the environment (eg. skills) for Android CLI.
+ Initializes the environment for the Android CLI. Sets up required
+ configurations, directories, and default skills.
+
+install
+ Usage: android install [-hv] [--use-delta-install] [--device=PARAM]
+ [--apks=PARAM[,PARAM...]]... [--install-options=PARAM[,
+ PARAM...]]...
+ Install an Android Application (one or more APKs) to a connected device or
+ emulator without activating any components using incremental optimizations for
+ faster deployment than adb.
+ --apks=PARAM[,PARAM...]
+ The paths to the APKs
+ --device=PARAM The device serial number
+ -h, --help Show this help message and exit.
+ --install-options=PARAM[,PARAM...]
+ Additional options/flags to pass to package manager
+ install (e.g. -g,-d)
+ --use-delta-install Use fast delta install (speeds up incremental
+ updates by transferring only modified code and
+ resources; default: true)
+ -v, --verbose Enable verbose logging
layout
Usage: android layout [-dhp] [--device=PARAM] [-o=PARAM]
@@ -173,16 +211,26 @@ layout
-p, --pretty Pretty-prints the returned JSON
run
- Usage: android run [-h] [--debug] [--activity=PARAM] [--device=PARAM]
- [--type=PARAM] [--apks=PARAM[,PARAM...]]...
- Deploy an Android Application
- --activity=PARAM The activity name
+ Usage: android run [-hv] [--debug] [--use-delta-install] [--activity=PARAM]
+ [--device=PARAM] [--type=PARAM] [--apks=PARAM[,PARAM...]]...
+ [--install-options=PARAM[,PARAM...]]...
+ Build, deploy, and launch an Android application on a connected device or
+ emulator.
+ --activity=PARAM The activity name
--apks=PARAM[,PARAM...]
- The paths to the APKs
- --debug Run in debug mode
- --device=PARAM The device serial number
- -h, --help Show this help message and exit.
- --type=PARAM The component type (ACTIVITY, SERVICE, etc.)
+ The paths to the APKs
+ --debug Run in debug mode
+ --device=PARAM The device serial number
+ -h, --help Show this help message and exit.
+ --install-options=PARAM[,PARAM...]
+ Additional options/flags to pass to package manager
+ install (e.g. -g,-d)
+ --type=PARAM The component type (ACTIVITY, WATCH_FACE, TILE,
+ COMPLICATION, DECLARATIVE_WATCH_FACE, WEAR_WIDGET)
+ --use-delta-install Use fast delta install (speeds up incremental
+ updates by transferring only modified code and
+ resources; default: false)
+ -v, --verbose Enable verbose logging
screen
Usage: android screen [-h] [COMMAND]
@@ -194,21 +242,25 @@ screen
sdk
Usage: android sdk [COMMAND]
- Download and list SDK packages
+ Manage the Android SDK installation. Includes commands to install, update,
+ remove, and list available and installed SDK packages.
Commands:
install Install SDK packages
update Update one or all packages to the latest version
- remove Remove a package from the SDK
+ remove Remove packages from the SDK
list List installed and available SDK packages
skills
- Usage: android skills [COMMAND]
- Manage skills
+ Usage: android skills [-h] [COMMAND]
+ Manage Android CLI skills. Includes commands to install, remove, list, and
+ search for skills by keyword.
+ -h, --help Show this help message and exit.
Commands:
- add Install a skill
- remove Remove a skill
- list List available skills
- find Find skills by keyword
+ add [id] Install a specific skill by its ID to your environment
+ remove [id] Remove an installed skill by its ID
+ list List installed and available skills
+ find [keyword] Search for available skills in the repository matching a
+ keyword
studio
Usage: android studio [-h] [COMMAND]
@@ -227,5 +279,6 @@ studio
update
Usage: android update [--url=PARAM]
- Update the Android CLI
+ Update the Android CLI to the latest version.
--url=PARAM The URL to download the update from
+
diff --git a/identity/verified-email/SKILL.md b/identity/verified-email/SKILL.md
index 784038e..0b8b191 100644
--- a/identity/verified-email/SKILL.md
+++ b/identity/verified-email/SKILL.md
@@ -8,7 +8,7 @@ description: Provides a complete workflow for implementing verified email retrie
license: Complete terms in LICENSE.txt
metadata:
author: Google LLC
- last-updated: '2026-07-02'
+ last-updated: '2026-08-06'
keywords:
- implementation
- Android
@@ -57,15 +57,11 @@ Email verification is applicable for the following use cases:
### Scope \& Pre-requisites
-**Crucial** : This skill focuses exclusively on the **Android client-side
-integration** . It does **not** implement the app's server-side cryptographic
-validation logic. Server-side validation of the returned credential is required
-for security and must be implemented in your backend.
+**Crucial** : This skill focuses exclusively on the **Android client-side integration** . It does **not** implement the app's server-side cryptographic validation logic. Server-side validation of the returned credential is required for security and must be implemented in your backend.
## Codebase exploration for Use Cases
-Get started with the following queries in project source code to find relevant
-screens with different use cases to implement verified email:
+Get started with the following queries in project source code to find relevant screens with different use cases to implement verified email:
- `SignUpScreen`
- `"Email address"`
@@ -76,14 +72,11 @@ screens with different use cases to implement verified email:
## Identifying Integration Points
-To implement this feature effectively, you must first locate the relevant
-flows in your codebase. To initiate, start with the following strategies to
-cater to different use cases using verified email:
+To implement this feature effectively, you must first locate the relevant flows in your codebase. To initiate, start with the following strategies to cater to different use cases using verified email:
### 1. Search for Navigation Routes
-If your app uses Navigation, search for routes or destinations related
-to authentication:
+If your app uses Navigation, search for routes or destinations related to authentication:
Look for:
@@ -92,16 +85,14 @@ Look for:
### 2. Locate Authentication ViewModels
-Find the business logic handling user attributes and account creation, account
-recovery:
+Find the business logic handling user attributes and account creation, account recovery:
- **Keywords** : `SignUpViewModel`, `AuthViewModel`, `RegistrationRepository`.
- **Code Pattern** : Look for methods like `onCreateAccount`, `onRecoverAccount`, or `validateEmail`.
### 3. Find instances of reauthentication for sensitive actions
-For reauthentication use cases, find areas where users perform sensitive
-actions:
+For reauthentication use cases, find areas where users perform sensitive actions:
- **Keywords** : `ChangePassword`, `UpdatePayment`, `DeleteAccount`, `UpdateDetails`, `EditUserDetails`
@@ -117,21 +108,20 @@ actions:
- Leave a TODO for developers to handle the app's server-side validation and parsing.
- Direct users to the home screen after API call success and show a snackbar with user details for reference purpose only.
-This guide describes how to implement verified email retrieval using the
-[Digital Credentials Verifier API](references/android/identity/digital-credentials/credential-verifier.md) through an [OpenID for Verifiable
-Presentations (OpenID4VP)](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html) request.
+## Overview
+
+This guide describes how to implement verified email retrieval using the [Digital Credentials Verifier API](references/android/identity/digital-credentials/credential-verifier.md) through an [OpenID for Verifiable Presentations (OpenID4VP)](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html) request.
## Add dependencies
-In your app's `build.gradle` file, add the following dependencies for Credential
-Manager:
+In your app's `build.gradle` file, add the following dependencies for Credential Manager:
### Kotlin
```kotlin
dependencies {
- implementation("androidx.credentials:credentials:1.7.0-alpha02")
- implementation("androidx.credentials:credentials-play-services-auth:1.7.0-alpha02")
+ implementation("androidx.credentials:credentials:1.7.0-alpha03")
+ implementation("androidx.credentials:credentials-play-services-auth:1.7.0-alpha03")
}
```
@@ -139,8 +129,8 @@ dependencies {
```groovy
dependencies {
- implementation "androidx.credentials:credentials:1.7.0-alpha02"
- implementation "androidx.credentials:credentials-play-services-auth:1.7.0-alpha02"
+ implementation "androidx.credentials:credentials:1.7.0-alpha03"
+ implementation "androidx.credentials:credentials-play-services-auth:1.7.0-alpha03"
}
```
@@ -154,14 +144,9 @@ Use your app or activity context to create a `CredentialManager` object.
## Construct the Digital Credential request
-To request a verified email, construct a [`GetCredentialRequest`](https://developer.android.com/reference/android/credentials/GetCredentialRequest)
-containing a [`GetDigitalCredentialOption`](https://developer.android.com/reference/androidx/credentials/GetDigitalCredentialOption). This option requires a
-`requestJson` string formatted as an OpenID for Verifiable Presentations
-(OpenID4VP) request.
+To request a verified email, construct a [`GetCredentialRequest`](https://developer.android.com/reference/android/credentials/GetCredentialRequest) containing a [`GetDigitalCredentialOption`](https://developer.android.com/reference/androidx/credentials/GetDigitalCredentialOption). This option requires a `requestJson` string formatted as an OpenID for Verifiable Presentations (OpenID4VP) request.
-The OpenID4VP request JSON must follow a specific structure. The current
-providers support a JSON structure with an outer `"digital": {"requests":
-[...]}` wrapper.
+The OpenID4VP request JSON must follow a specific structure. The current providers support a JSON structure with an outer `"digital": {"requests": [...]}` wrapper.
val nonce = generateSecureRandomNonce()
@@ -206,26 +191,19 @@ providers support a JSON structure with an outer `"digital": {"requests":
The request contains the following key information:
-- **DCQL query** : The `dcql_query` specifies the credential type and the
- claims being requested (`email_verified`). You can request other claims to
- determine the level of verification. A few possible claims are as follows:
+- **DCQL query** : The `dcql_query` specifies the credential type and the claims being requested (`email_verified`). You can request other claims to determine the level of verification. A few possible claims are as follows:
- `email_verified`: In the response, this is a Boolean that indicates whether the email is verified.
- `hd` (hosted domain): In the response, this is empty.
> [!NOTE]
- > **Note:** If `email_verified` is `true` and `hd` is empty in the response, it implies that the account is an authorized Google Account. Google does not issue [verifiable credentials](references/android/identity/digital-credentials/index.md) for Google Workspace Accounts. However, the `hd` field is present in verifiable credentials issued for non-workspace accounts. You are encouraged to implement handling this field to future-proof your app. If the email is non-@gmail.com, Google verified this email when the Google Account was created, but there is no freshness claim. Therefore, for non-Google emails, you should consider an additional challenge, such as an OTP, to verify the user. To understand the schema of the credential and the specific rules for validating fields like `email_verified`, refer to the [Google
- > Identity guides](https://developers.google.com/identity/gsi/web/guides/verify-google-id-token).
+ > **Note:** If `email_verified` is `true` and `hd` is empty in the response, it implies that the account is an authorized Google Account. Google does not issue [verifiable credentials](references/android/identity/digital-credentials/index.md) for Google Workspace Accounts. However, the `hd` field is present in verifiable credentials issued for non-workspace accounts. You are encouraged to implement handling this field to future-proof your app. If the email is non-@gmail.com, Google verified this email when the Google Account was created, but there is no freshness claim. Therefore, for non-Google emails, you should consider an additional challenge, such as an OTP, to verify the user. To understand the schema of the credential and the specific rules for validating fields like `email_verified`, refer to the [Google Identity guides](https://developers.google.com/identity/gsi/web/guides/verify-google-id-token).
-- **nonce**: A unique, cryptographically secure random value is generated for
- each request. This is critical for security, as it prevents replay attacks.
+- **nonce**: A unique, cryptographically secure random value is generated for each request. This is critical for security, as it prevents replay attacks.
-- `UserInfoCredential`: This value implies a specific type of digital
- credential that contains user attributes. Including this in the request is
- pivotal to distinguish the email verification use case.
+- `UserInfoCredential`: This value implies a specific type of digital credential that contains user attributes. Including this in the request is pivotal to distinguish the email verification use case.
-Next, wrap the `openId4vpRequest` JSON in a `GetDigitalCredentialOption`, create
-a `GetCredentialRequest`, and call `getCredential()`.
+Next, wrap the `openId4vpRequest` JSON in a `GetDigitalCredentialOption`, create a `GetCredentialRequest`, and call `getCredential()`.
> [!NOTE]
> **Note:** The `hd` and `email_verified` fields are hidden from users in Credential Manager's built-in UI. You cannot make a request with only these hidden fields- in case of such requests, the response is the [`GetCredentialCancellationException`](https://developer.android.com/reference/kotlin/androidx/credentials/exceptions/GetCredentialCancellationException).
@@ -261,15 +239,12 @@ Present the user with the request, using the Credential Manager built-in UI.
## Parse the response on the client
-After receiving the response, you can perform a preliminary parse on the client.
-This is useful for immediately updating the UI, for example, by showing the
-user's name.
+After receiving the response, you can perform a preliminary parse on the client. This is useful for immediately updating the UI, for example, by showing the user's name.
> [!IMPORTANT]
> **Important:** This step is not for validation. Full cryptographic verification must be performed on your server.
-The following code extracts the raw [Selective Disclosure JWT
-(SD-JWT)](https://datatracker.ietf.org/doc/rfc9901/) and uses a helper to decode its claims.
+The following code extracts the raw [Selective Disclosure JWT (SD-JWT)](https://datatracker.ietf.org/doc/rfc9901/) and uses a helper to decode its claims.
// 1. Parse the outer JSON wrapper to get the `vp_token`
val responseData = JSONObject(responseJsonString)
@@ -294,12 +269,9 @@ The following code extracts the raw [Selective Disclosure JWT
## Handle the response
-The Credential Manager API will return a [`DigitalCredential`](https://developer.android.com/reference/androidx/credentials/DigitalCredential)
-response.
+The Credential Manager API will return a [`DigitalCredential`](https://developer.android.com/reference/androidx/credentials/DigitalCredential) response.
-The following is an example of what the raw `responseJsonString` looks like, and
-what the claims look like after parsing the inner SD-JWT where you get
-additional metadata as well along with verified email:
+The following is an example of what the raw `responseJsonString` looks like, and what the claims look like after parsing the inner SD-JWT where you get additional metadata as well along with verified email:
/*
// Example of the raw JSON response from credential.credentialJson:
@@ -337,18 +309,11 @@ additional metadata as well along with verified email:
## Server-side validation for account creation
-Since the retrieved email is cryptographically verified, you can omit the email
-OTP verification step, significantly reducing sign-up friction and potentially
-increasing conversion. This process is best handled on your server. The client
-sends the raw response (containing the `vp_token`) and the original nonce to a
-new server endpoint.
+Since the retrieved email is cryptographically verified, you can omit the email OTP verification step, significantly reducing sign-up friction and potentially increasing conversion. This process is best handled on your server. The client sends the raw response (containing the `vp_token`) and the original nonce to a new server endpoint.
-For verification, your application must send the full `responseJsonString` to
-your server for cryptographic validation before creating an account or logging
-the user in.
+For verification, your application must send the full `responseJsonString` to your server for cryptographic validation before creating an account or logging the user in.
-The digital credential provides two critical levels of verification for your
-server:
+The digital credential provides two critical levels of verification for your server:
- **Authenticity of the data** : Verifying the issuer (`iss`) URL and the `SD-JWT` signature proves that a trusted authority issued this data.
- **Identity of the presenter** : Verifying the `cnf` field and the Key Binding (`kb`) signature confirms that the credential is being shared by the same device it was originally issued to, preventing it from being intercepted or used on another device.
@@ -359,15 +324,11 @@ The validation on the server must achieve the following:
- **Verify signature**: Check the signature of the SD-JWT using the public keys (JWKs) available at https://verifiablecredentials-pa.googleapis.com/.well-known/vc-public-jwks.
> [!NOTE]
-> **Note:** Use a standard library (such as [@sd-jwt/sd-jwt-vc](https://datatracker.ietf.org/doc/rfc9901/) for Node.js) to perform the verification steps as outlined in the [OpenID for Verifiable
-> Presentations specification](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html).
+> **Note:** Use a standard library (such as [@sd-jwt/sd-jwt-vc](https://datatracker.ietf.org/doc/rfc9901/) for Node.js) to perform the verification steps as outlined in the [OpenID for Verifiable Presentations specification](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html).
-For full security, make sure that you also validate the `nonce` to prevent
-replay attacks.
+For full security, make sure that you also validate the `nonce` to prevent replay attacks.
-By combining these steps, your server can validate both the authenticity of the
-data and the identity of the presenter, ensuring the credential wasn't
-intercepted or spoofed before provisioning the new account.
+By combining these steps, your server can validate both the authenticity of the data and the identity of the presenter, ensuring the credential wasn't intercepted or spoofed before provisioning the new account.
try {
// Send the raw credential response and the original nonce to your server.
@@ -390,17 +351,11 @@ intercepted or spoofed before provisioning the new account.
## Passkey creation
-An optional but highly recommended next step after provisioning an account is to
-immediately [create a passkey](references/android/identity/passkeys/create-passkeys.md) for that account. This provides a secure,
-passwordless method for the user to sign in. This flow is identical to a
-standard passkey registration.
+An optional but highly recommended next step after provisioning an account is to immediately [create a passkey](references/android/identity/passkeys/create-passkeys.md) for that account. This provides a secure, passwordless method for the user to sign in. This flow is identical to a standard passkey registration.
## WebView support
-For the flow to work on a [`WebView`](https://developer.android.com/reference/android/webkit/WebView), developers should implement a
-[JavaScript bridge](references/android/identity/sign-in/credential-manager-webview.md) (JS Bridge) to facilitate the handoff. This bridge
-allows the `WebView` object to signal the native app, which can then perform the
-actual call to the Credential Manager API.
+For the flow to work on a [`WebView`](https://developer.android.com/reference/android/webkit/WebView), developers should implement a [JavaScript bridge](references/android/identity/sign-in/credential-manager-webview.md) (JS Bridge) to facilitate the handoff. This bridge allows the `WebView` object to signal the native app, which can then perform the actual call to the Credential Manager API.
## See also
@@ -409,8 +364,7 @@ actual call to the Credential Manager API.
## Critical Security Guidelines
-To maintain the integrity of the email verification flow, the following security
-requirements are mandatory:
+To maintain the integrity of the email verification flow, the following security requirements are mandatory:
- **Server-side Validation** : Never trust claims parsed on the client for security-sensitive operations like account creation. Send the complete, raw `responseJsonString` and the original `nonce` to the app's server for full verification.
- **Nonce Integrity** : Generate a unique, cryptographically secure nonce for every request and **never** reuse a nonce across multiple requests to prevent replay attacks.
diff --git a/identity/verified-email/references/android/identity/credential-manager/index.md b/identity/verified-email/references/android/identity/credential-manager/index.md
index c646f19..d11d29b 100644
--- a/identity/verified-email/references/android/identity/credential-manager/index.md
+++ b/identity/verified-email/references/android/identity/credential-manager/index.md
@@ -1,21 +1,15 @@
-[Credential Manager](https://developer.android.com/reference/kotlin/androidx/credentials/package-summary) is the recommended Jetpack API for credential exchange
-in Android apps. The Credential Manager API streamlines credential exchange
-across form factors for use cases spanning authentication and authorization. You
-can also use Credential Manager to handle digital credentials and restore user
-credentials on new Android devices.
+[Credential Manager](https://developer.android.com/reference/kotlin/androidx/credentials/package-summary) is the recommended Jetpack API for credential exchange in Android apps. The Credential Manager API streamlines credential exchange across form factors for use cases spanning authentication and authorization. You can also use Credential Manager to handle digital credentials and restore user credentials on new Android devices.
## Credential Manager features
-Credential Manager streamlines the sign-in process and enhances security by
-offering a robust set of capabilities, including:
+Credential Manager streamlines the sign-in process and enhances security by offering a robust set of capabilities, including:
- **Support for various authentication mechanisms** : Enables users to sign up or sign in to your app using:
- [Passkeys](https://developer.android.com/identity/passkeys)
- [Sign-in with Google](https://developer.android.com/identity/sign-in/credential-manager-siwg) and other federated sign-in mechanisms
- [Passwords](https://developer.android.com/identity/passwords)
- [Digital credentials](https://developer.android.com/identity/digital-credentials)
-- **Cross-device credential restore** : Provides integration with [Restore
- Credentials](https://developer.android.com/identity/sign-in/restore-credentials), allowing users to seamlessly start using your app on a new device.
+- **Cross-device credential restore** : Provides integration with [Restore Credentials](https://developer.android.com/identity/sign-in/restore-credentials), allowing users to seamlessly start using your app on a new device.
- **Seamless integration with credential providers** : Offers support for [credential providers](https://developer.android.com/identity/sign-in/credential-provider), including password managers such as Google Password Manager.
- **Credential management**: Enables updating the metadata for user credentials, helping to keep credentials consistent across your app and credential providers.
- **WebView compatibility** : Works with apps that use [WebView](https://developer.android.com/identity/sign-in/credential-manager-webview).
@@ -23,12 +17,10 @@ offering a robust set of capabilities, including:
## Benefits of using Credential Manager
-Adopting Credential Manager provides several key advantages for both your
-application and your users:
+Adopting Credential Manager provides several key advantages for both your application and your users:
- **Enhanced security**: Passkeys offer enhanced security and protect users from phishing attempts.
-- **Support for various form factors** : The APIs work across Android [form
- factors](https://developer.android.com/identity/form-factors), including mobile, Android XR, and Wear OS devices.
+- **Support for various form factors** : The APIs work across Android [form factors](https://developer.android.com/identity/form-factors), including mobile, Android XR, and Wear OS devices.
- **Simplified authentication across use cases** : [Digital credentials](https://developer.android.com/identity/digital-credentials), such as digital driver's licenses, corporate IDs, and national ID cards, enable authentication across various use cases, including those requiring [phone number verification](https://developer.android.com/identity/digital-credentials/phone-number-verification).
- **Improved user experience**: Credential Manager's unified interface gives users a familiar and consistent experience and improves registration and sign-in speeds. The bottom sheet UI appears inline to your app's content, so your users remain within your app's context during sign-in. The following image shows Credential Manager's built-in UI:
@@ -36,8 +28,7 @@ application and your users:
## Authentication terminology
-An entity that requires authentication for its users is known as a **relying
-party**. An authentication workflow typically includes the following components:
+An entity that requires authentication for its users is known as a **relying party**. An authentication workflow typically includes the following components:
- **Relying party client app**: The client---in this case, your Android app---that handles the user interface to create and use passkeys.
- **Relying party server**: An app server that helps with the creation, storage, and verification of passkeys.
@@ -45,21 +36,13 @@ party**. An authentication workflow typically includes the following components:
## Credential storage
-Credential providers, such as Google Password Manager, provide a centralized and
-secure location for users to manage credentials across their devices, further
-simplifying the authentication process. To integrate with Credential Manager as
-a credential provider, see
-[Implement authentication as a credential provider](https://developer.android.com/identity/sign-in/credential-provider).
+Credential providers, such as Google Password Manager, provide a centralized and secure location for users to manage credentials across their devices, further simplifying the authentication process. To integrate with Credential Manager as a credential provider, see [Implement authentication as a credential provider](https://developer.android.com/identity/sign-in/credential-provider).
-For more information about how Google Password Manager keeps your credentials
-secure, see
-[Security of Passkeys in the Google Password Manager](https://security.googleblog.com/2022/10/SecurityofPasskeysintheGooglePasswordManager.html).
+For more information about how Google Password Manager keeps your credentials secure, see [Security of Passkeys in the Google Password Manager](https://security.googleblog.com/2022/10/SecurityofPasskeysintheGooglePasswordManager.html).
## Migrate to Credential Manager
-Credential Manager is intended to replace legacy Android authentication APIs and
-local FIDO2 credentials. For more information about migrating to Credential
-Manager, see the following guides:
+Credential Manager is intended to replace legacy Android authentication APIs and local FIDO2 credentials. For more information about migrating to Credential Manager, see the following guides:
- [Google Sign-In](https://developer.android.com/identity/sign-in/legacy-gsi-migration)
- [One Tap](https://developer.android.com/identity/legacy/one-tap)
diff --git a/identity/verified-email/references/android/identity/digital-credentials/credential-verifier.md b/identity/verified-email/references/android/identity/digital-credentials/credential-verifier.md
index 3f7f9c9..082ada7 100644
--- a/identity/verified-email/references/android/identity/digital-credentials/credential-verifier.md
+++ b/identity/verified-email/references/android/identity/digital-credentials/credential-verifier.md
@@ -1,14 +1,6 @@
-Digital credential verification within Android apps can be used to authenticate
-and authorize a user's identity (such as a government ID), properties about that
-user (such as a driver's license, academic degree, or attributes such as age or
-address), or other scenarios where a credential needs to be issued and verified
-to assert the authenticity of an entity.
+Digital credential verification within Android apps can be used to authenticate and authorize a user's identity (such as a government ID), properties about that user (such as a driver's license, academic degree, or attributes such as age or address), or other scenarios where a credential needs to be issued and verified to assert the authenticity of an entity.
-Digital Credentials is a public W3C standard that specifies how to access a
-user's verifiable digital credentials from a digital wallet, and is implemented
-for web use cases with the [W3C Credential Management API](https://www.w3.org/TR/credential-management-1/). On
-Android, Credential Manager's [`DigitalCredential`](https://developer.android.com/reference/kotlin/androidx/credentials/DigitalCredential) API is used for
-verifying digital credentials.
+Digital Credentials is a public W3C standard that specifies how to access a user's verifiable digital credentials from a digital wallet, and is implemented for web use cases with the [W3C Credential Management API](https://www.w3.org/TR/credential-management-1/). On Android, Credential Manager's [`DigitalCredential`](https://developer.android.com/reference/kotlin/androidx/credentials/DigitalCredential) API is used for verifying digital credentials.
### Android version compatibility
@@ -37,8 +29,7 @@ Next, Initialize an instance of the `CredentialManager` class.
#### Construct a digital credential request
-Construct a digital credential request and use it to initialize a
-`DigitalCredentialOption`.
+Construct a digital credential request and use it to initialize a `DigitalCredentialOption`.
// The request in the JSON format to conform with
// the JSON-ified Credential Manager - Verifier API request definition.
@@ -51,8 +42,7 @@ Construct a digital credential request and use it to initialize a
listOf(digitalCredentialOption)
)
-Here is an example of an OpenId4Vp request. A full reference can be found at
-this [website](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html).
+Here is an example of an OpenId4Vp request. A full reference can be found at this [website](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html).
{
"requests": [
@@ -100,14 +90,9 @@ this [website](https://openid.net/specs/openid-4-verifiable-presentations-1_0.ht
#### Get the credential
-Launch the `getCredential` flow with the constructed request. You will receive
-either a successful `GetCredentialResponse`, or a `GetCredentialException` if
-the request fails.
+Launch the `getCredential` flow with the constructed request. You will receive either a successful `GetCredentialResponse`, or a `GetCredentialException` if the request fails.
-The `getCredential` flow triggers Android system dialogs to present the user's
-available credential options and collect their selection. Next, the wallet app
-that contains the chosen credential option will display UIs to collect consent
-and perform actions needed to generate a digital credential response.
+The `getCredential` flow triggers Android system dialogs to present the user's available credential options and collect their selection. Next, the wallet app that contains the chosen credential option will display UIs to collect consent and perform actions needed to generate a digital credential response.
coroutineScope.launch {
try {
diff --git a/identity/verified-email/references/android/identity/digital-credentials/email-verification-implementation.md b/identity/verified-email/references/android/identity/digital-credentials/email-verification-implementation.md
index 9305e92..048f11b 100644
--- a/identity/verified-email/references/android/identity/digital-credentials/email-verification-implementation.md
+++ b/identity/verified-email/references/android/identity/digital-credentials/email-verification-implementation.md
@@ -1,22 +1,31 @@
-> [!IMPORTANT]
-> **Important:** We released an agent skill to help you implement email verification with the Digital Credentials API. Try out the skill from the [Android skills
-> repository](https://github.com/android/skills).
+
-This guide describes how to implement verified email retrieval using the
-[Digital Credentials Verifier API](https://developer.android.com/identity/digital-credentials/credential-verifier) through an [OpenID for Verifiable
-Presentations (OpenID4VP)](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html) request.
+## Android skills
+
+[View on GitHub](https://github.com/android/skills/tree/main/identity/verified-email)
+
+### Retrieve verified email
+
+Use an Android skill to integrate a secure, OTP-less email verification flow into your app. To install the skill from the [Android CLI](https://developer.android.com/tools/agents/android-cli), run:
+
+ android skills add --skill verified-email
+
+
+
+## Overview
+
+This guide describes how to implement verified email retrieval using the [Digital Credentials Verifier API](https://developer.android.com/identity/digital-credentials/credential-verifier) through an [OpenID for Verifiable Presentations (OpenID4VP)](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html) request.
## Add dependencies
-In your app's `build.gradle` file, add the following dependencies for Credential
-Manager:
+In your app's `build.gradle` file, add the following dependencies for Credential Manager:
### Kotlin
```kotlin
dependencies {
- implementation("androidx.credentials:credentials:1.7.0-alpha02")
- implementation("androidx.credentials:credentials-play-services-auth:1.7.0-alpha02")
+ implementation("androidx.credentials:credentials:1.7.0-alpha03")
+ implementation("androidx.credentials:credentials-play-services-auth:1.7.0-alpha03")
}
```
@@ -24,8 +33,8 @@ dependencies {
```groovy
dependencies {
- implementation "androidx.credentials:credentials:1.7.0-alpha02"
- implementation "androidx.credentials:credentials-play-services-auth:1.7.0-alpha02"
+ implementation "androidx.credentials:credentials:1.7.0-alpha03"
+ implementation "androidx.credentials:credentials-play-services-auth:1.7.0-alpha03"
}
```
@@ -39,14 +48,9 @@ Use your app or activity context to create a `CredentialManager` object.
## Construct the Digital Credential request
-To request a verified email, construct a [`GetCredentialRequest`](https://developer.android.com/reference/android/credentials/GetCredentialRequest)
-containing a [`GetDigitalCredentialOption`](https://developer.android.com/reference/androidx/credentials/GetDigitalCredentialOption). This option requires a
-`requestJson` string formatted as an OpenID for Verifiable Presentations
-(OpenID4VP) request.
+To request a verified email, construct a [`GetCredentialRequest`](https://developer.android.com/reference/android/credentials/GetCredentialRequest) containing a [`GetDigitalCredentialOption`](https://developer.android.com/reference/androidx/credentials/GetDigitalCredentialOption). This option requires a `requestJson` string formatted as an OpenID for Verifiable Presentations (OpenID4VP) request.
-The OpenID4VP request JSON must follow a specific structure. The current
-providers support a JSON structure with an outer `"digital": {"requests":
-[...]}` wrapper.
+The OpenID4VP request JSON must follow a specific structure. The current providers support a JSON structure with an outer `"digital": {"requests": [...]}` wrapper.
val nonce = generateSecureRandomNonce()
@@ -91,26 +95,19 @@ providers support a JSON structure with an outer `"digital": {"requests":
The request contains the following key information:
-- **DCQL query** : The `dcql_query` specifies the credential type and the
- claims being requested (`email_verified`). You can request other claims to
- determine the level of verification. A few possible claims are as follows:
+- **DCQL query** : The `dcql_query` specifies the credential type and the claims being requested (`email_verified`). You can request other claims to determine the level of verification. A few possible claims are as follows:
- `email_verified`: In the response, this is a Boolean that indicates whether the email is verified.
- `hd` (hosted domain): In the response, this is empty.
> [!NOTE]
- > **Note:** If `email_verified` is `true` and `hd` is empty in the response, it implies that the account is an authorized Google Account. Google does not issue [verifiable credentials](https://developer.android.com/identity/digital-credentials#verifiable-credentials) for Google Workspace Accounts. However, the `hd` field is present in verifiable credentials issued for non-workspace accounts. You are encouraged to implement handling this field to future-proof your app. If the email is non-@gmail.com, Google verified this email when the Google Account was created, but there is no freshness claim. Therefore, for non-Google emails, you should consider an additional challenge, such as an OTP, to verify the user. To understand the schema of the credential and the specific rules for validating fields like `email_verified`, refer to the [Google
- > Identity guides](https://developers.google.com/identity/gsi/web/guides/verify-google-id-token).
+ > **Note:** If `email_verified` is `true` and `hd` is empty in the response, it implies that the account is an authorized Google Account. Google does not issue [verifiable credentials](https://developer.android.com/identity/digital-credentials#verifiable-credentials) for Google Workspace Accounts. However, the `hd` field is present in verifiable credentials issued for non-workspace accounts. You are encouraged to implement handling this field to future-proof your app. If the email is non-@gmail.com, Google verified this email when the Google Account was created, but there is no freshness claim. Therefore, for non-Google emails, you should consider an additional challenge, such as an OTP, to verify the user. To understand the schema of the credential and the specific rules for validating fields like `email_verified`, refer to the [Google Identity guides](https://developers.google.com/identity/gsi/web/guides/verify-google-id-token).
-- **nonce**: A unique, cryptographically secure random value is generated for
- each request. This is critical for security, as it prevents replay attacks.
+- **nonce**: A unique, cryptographically secure random value is generated for each request. This is critical for security, as it prevents replay attacks.
-- `UserInfoCredential`: This value implies a specific type of digital
- credential that contains user attributes. Including this in the request is
- pivotal to distinguish the email verification use case.
+- `UserInfoCredential`: This value implies a specific type of digital credential that contains user attributes. Including this in the request is pivotal to distinguish the email verification use case.
-Next, wrap the `openId4vpRequest` JSON in a `GetDigitalCredentialOption`, create
-a `GetCredentialRequest`, and call `getCredential()`.
+Next, wrap the `openId4vpRequest` JSON in a `GetDigitalCredentialOption`, create a `GetCredentialRequest`, and call `getCredential()`.
> [!NOTE]
> **Note:** The `hd` and `email_verified` fields are hidden from users in Credential Manager's built-in UI. You cannot make a request with only these hidden fields- in case of such requests, the response is the [`GetCredentialCancellationException`](https://developer.android.com/reference/kotlin/androidx/credentials/exceptions/GetCredentialCancellationException).
@@ -146,15 +143,12 @@ Present the user with the request, using the Credential Manager built-in UI.
## Parse the response on the client
-After receiving the response, you can perform a preliminary parse on the client.
-This is useful for immediately updating the UI, for example, by showing the
-user's name.
+After receiving the response, you can perform a preliminary parse on the client. This is useful for immediately updating the UI, for example, by showing the user's name.
> [!IMPORTANT]
> **Important:** This step is not for validation. Full cryptographic verification must be performed on your server.
-The following code extracts the raw [Selective Disclosure JWT
-(SD-JWT)](https://datatracker.ietf.org/doc/rfc9901/) and uses a helper to decode its claims.
+The following code extracts the raw [Selective Disclosure JWT (SD-JWT)](https://datatracker.ietf.org/doc/rfc9901/) and uses a helper to decode its claims.
// 1. Parse the outer JSON wrapper to get the `vp_token`
val responseData = JSONObject(responseJsonString)
@@ -179,12 +173,9 @@ The following code extracts the raw [Selective Disclosure JWT
## Handle the response
-The Credential Manager API will return a [`DigitalCredential`](https://developer.android.com/reference/androidx/credentials/DigitalCredential)
-response.
+The Credential Manager API will return a [`DigitalCredential`](https://developer.android.com/reference/androidx/credentials/DigitalCredential) response.
-The following is an example of what the raw `responseJsonString` looks like, and
-what the claims look like after parsing the inner SD-JWT where you get
-additional metadata as well along with verified email:
+The following is an example of what the raw `responseJsonString` looks like, and what the claims look like after parsing the inner SD-JWT where you get additional metadata as well along with verified email:
/*
// Example of the raw JSON response from credential.credentialJson:
@@ -222,18 +213,11 @@ additional metadata as well along with verified email:
## Server-side validation for account creation
-Since the retrieved email is cryptographically verified, you can omit the email
-OTP verification step, significantly reducing sign-up friction and potentially
-increasing conversion. This process is best handled on your server. The client
-sends the raw response (containing the `vp_token`) and the original nonce to a
-new server endpoint.
+Since the retrieved email is cryptographically verified, you can omit the email OTP verification step, significantly reducing sign-up friction and potentially increasing conversion. This process is best handled on your server. The client sends the raw response (containing the `vp_token`) and the original nonce to a new server endpoint.
-For verification, your application must send the full `responseJsonString` to
-your server for cryptographic validation before creating an account or logging
-the user in.
+For verification, your application must send the full `responseJsonString` to your server for cryptographic validation before creating an account or logging the user in.
-The digital credential provides two critical levels of verification for your
-server:
+The digital credential provides two critical levels of verification for your server:
- **Authenticity of the data** : Verifying the issuer (`iss`) URL and the `SD-JWT` signature proves that a trusted authority issued this data.
- **Identity of the presenter** : Verifying the `cnf` field and the Key Binding (`kb`) signature confirms that the credential is being shared by the same device it was originally issued to, preventing it from being intercepted or used on another device.
@@ -244,15 +228,11 @@ The validation on the server must achieve the following:
- **Verify signature**: Check the signature of the SD-JWT using the public keys (JWKs) available at https://verifiablecredentials-pa.googleapis.com/.well-known/vc-public-jwks.
> [!NOTE]
-> **Note:** Use a standard library (such as [@sd-jwt/sd-jwt-vc](https://datatracker.ietf.org/doc/rfc9901/) for Node.js) to perform the verification steps as outlined in the [OpenID for Verifiable
-> Presentations specification](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html).
+> **Note:** Use a standard library (such as [@sd-jwt/sd-jwt-vc](https://datatracker.ietf.org/doc/rfc9901/) for Node.js) to perform the verification steps as outlined in the [OpenID for Verifiable Presentations specification](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html).
-For full security, make sure that you also validate the `nonce` to prevent
-replay attacks.
+For full security, make sure that you also validate the `nonce` to prevent replay attacks.
-By combining these steps, your server can validate both the authenticity of the
-data and the identity of the presenter, ensuring the credential wasn't
-intercepted or spoofed before provisioning the new account.
+By combining these steps, your server can validate both the authenticity of the data and the identity of the presenter, ensuring the credential wasn't intercepted or spoofed before provisioning the new account.
try {
// Send the raw credential response and the original nonce to your server.
@@ -275,17 +255,11 @@ intercepted or spoofed before provisioning the new account.
## Passkey creation
-An optional but highly recommended next step after provisioning an account is to
-immediately [create a passkey](https://developer.android.com/identity/passkeys/create-passkeys) for that account. This provides a secure,
-passwordless method for the user to sign in. This flow is identical to a
-standard passkey registration.
+An optional but highly recommended next step after provisioning an account is to immediately [create a passkey](https://developer.android.com/identity/passkeys/create-passkeys) for that account. This provides a secure, passwordless method for the user to sign in. This flow is identical to a standard passkey registration.
## WebView support
-For the flow to work on a [`WebView`](https://developer.android.com/reference/android/webkit/WebView), developers should implement a
-[JavaScript bridge](https://developer.android.com/identity/sign-in/credential-manager-webview) (JS Bridge) to facilitate the handoff. This bridge
-allows the `WebView` object to signal the native app, which can then perform the
-actual call to the Credential Manager API.
+For the flow to work on a [`WebView`](https://developer.android.com/reference/android/webkit/WebView), developers should implement a [JavaScript bridge](https://developer.android.com/identity/sign-in/credential-manager-webview) (JS Bridge) to facilitate the handoff. This bridge allows the `WebView` object to signal the native app, which can then perform the actual call to the Credential Manager API.
## See also
diff --git a/identity/verified-email/references/android/identity/digital-credentials/email-verification.md b/identity/verified-email/references/android/identity/digital-credentials/email-verification.md
index 2134577..66a5f1a 100644
--- a/identity/verified-email/references/android/identity/digital-credentials/email-verification.md
+++ b/identity/verified-email/references/android/identity/digital-credentials/email-verification.md
@@ -1,7 +1,4 @@
-This document describes using Credential Manager to get a cryptographically
-verified email address from a user's device. This process removes the need for
-your app users to verify their email with one-time passwords (OTPs) or magic
-links.
+This document describes using Credential Manager to get a cryptographically verified email address from a user's device. This process removes the need for your app users to verify their email with one-time passwords (OTPs) or magic links.
This document explains the following areas:
@@ -19,90 +16,66 @@ This guide assumes you are familiar with the following concepts:
## Android compatibility
-This feature is supported on mobiles, tablets, and foldable devices running
-Android 9 (API level 28) and higher. The minimum version of Google Play services
-(GMS) required is 25.49.x.
+This feature is supported on mobiles, tablets, and foldable devices running Android 9 (API level 28) and higher. The minimum version of Google Play services (GMS) required is 25.49.x.
## User experience
-The following sections describe the user experience during the verification
-flow, the need to include fallback verification methods, as well as the
-recommended user experience for various use cases.
+The following sections describe the user experience during the verification flow, the need to include fallback verification methods, as well as the recommended user experience for various use cases.
### The verification flow
The user experience for sharing a verified email is as follows:
-1. The user either focuses on an input field or taps a button that calls the
- Credential Manager API. Depending on the design of the screen, you can also
- call the API on your app's screen load.
+1. The user either focuses on an input field or taps a button that calls the Credential Manager API. Depending on the design of the screen, you can also call the API on your app's screen load.
-2. A bottom sheet appears, showing the information that will be shared with the
- app. If no information is available on that device, the user sees a generic
- error message.
+2. A bottom sheet appears, showing the information that will be shared with the app. If no information is available on that device, the user sees a generic error message.
-3. After the user taps **Agree and Continue**, display a success or failure
- message.
+3. After the user taps **Agree and Continue**, display a success or failure message.
> [!NOTE]
> **Note:** If the verified email you receive does not match what you expect, inform the user about the mismatch and either ask them to try again with a different credential or provide an alternate verification method, such as through OTPs.
-4. (Optional, recommended) If the user is signing up for your service, you
- should prompt the user to [create](https://developer.android.com/identity/passkeys/create-passkeys) a [passkey](https://developer.android.com/identity/passkeys) to make it easier for
- them to sign in subsequently.
+4. (Optional, recommended) If the user is signing up for your service, you should prompt the user to [create](https://developer.android.com/identity/passkeys/create-passkeys) a [passkey](https://developer.android.com/identity/passkeys) to make it easier for them to sign in subsequently.
> [!NOTE]
> **Note:** The email verification process doesn't automatically trigger passkey creation. However, it is highly recommended to include the steps for passkey creation. Passkeys help users by making it easier and more secure for them to sign in, and remove the need for the conventional username and password interaction.
### Include primary and fallback flows
-To ensure a streamlined user experience, include the following options on
-screens that require email verification:
+To ensure a streamlined user experience, include the following options on screens that require email verification:
- **Primary verification option**: An email field or button to trigger the Credential Manager API flow for quick verification.
- **Alternate verification options**: A link or button for users to "Verify another way" or with "Other options" for manual email entry in case of failures, such as no information available on the device, or a mismatch between the retrieved and expected email. This should allow users to try verification with a different credential or by providing a manual OTP.
### Use cases
-The following sections describe the recommended use cases, as well as the
-suggested user experience, for email verification.
+The following sections describe the recommended use cases, as well as the suggested user experience, for email verification.
#### Sign up
-Users can immediately create an account with a verified email without a separate
-verification step. Optionally, prompt the user to add a passkey. If they opt to
-add a passkey, trigger the [passkey creation](https://developer.android.com/identity/passkeys/create-passkeys) flow.
+Users can immediately create an account with a verified email without a separate verification step. Optionally, prompt the user to add a passkey. If they opt to add a passkey, trigger the [passkey creation](https://developer.android.com/identity/passkeys/create-passkeys) flow.
 Email verification during sign up
#### Account recovery
-To eliminate the frustration of users searching for recovery codes in their spam
-folders, allow them to recover their account using the verified email securely
-stored on their device. Additionally, suggest that they create a passkey for
-future use.
+To eliminate the frustration of users searching for recovery codes in their spam folders, allow them to recover their account using the verified email securely stored on their device. Additionally, suggest that they create a passkey for future use.
 Email verification during account recovery
#### Reauthentication for sensitive actions
-Protect sensitive user actions, such as changing settings or updating profile
-details, by requiring a quick reauthentication step.
+Protect sensitive user actions, such as changing settings or updating profile details, by requiring a quick reauthentication step.
 Email verification during reauthentication
## Accounts supported
-Email verification through Credential Manager only supports verification of
-consumer Google Accounts. [Workspace accounts](https://knowledge.workspace.google.com/admin/getting-started/set-up-google-workspace-for-your-organization) and [supervised
-accounts](https://support.google.com/families/answer/9499054) are not supported.
+Email verification through Credential Manager only supports verification of consumer Google Accounts. [Workspace accounts](https://knowledge.workspace.google.com/admin/getting-started/set-up-google-workspace-for-your-organization) and [supervised accounts](https://support.google.com/families/answer/9499054) are not supported.
-A consumer Google Account can be created with an email address from any
-provider, not necessarily @gmail.com. However, Google verifies these accounts
-differently:
+A consumer Google Account can be created with an email address from any provider, not necessarily @gmail.com. However, Google verifies these accounts differently:
- For @gmail.com accounts: Google is the authoritative source, and the email is known to be verified.
- For non-@gmail.com accounts: Google is not the authoritative source for these email addresses in the long term. While Google verifies the email when the account is created, the ownership of that email address might change over time. Therefore, for non-@gmail.com addresses, you should consider an additional verification step, such as sending an OTP, to ensure that the user still has access to the email account.
-For more information about what verification implies, see [Digital
-Credentials](https://developer.android.com/identity/digital-credentials#verified).
+For more information about what verification implies, see [Digital Credentials](https://developer.android.com/identity/digital-credentials#verified).
> [!NOTE]
> **Note:** Apart from a user's email information, you can request other unverified fields, such as the user's given name, family name, name, and the profile picture of their Google Account. However, only the email is verified by Google.
@@ -110,30 +83,19 @@ Credentials](https://developer.android.com/identity/digital-credentials#verified
## Validity and freshness
-The system issues [verifiable credentials](https://developer.android.com/identity/digital-credentials#verified) (VCs) based on the user's current
-email from the active Google Accounts on the device. These credentials are
-issued to the device in advance, typically while the device is idle. While these
-credentials might remain valid for multiple days, the system performs a check at
-the moment of sharing the credentials to ensure that the account still exists,
-is on the device, and that the email address is valid---effectively prioritizing
-the account's immediate status over the credential's validity window.
+The system issues [verifiable credentials](https://developer.android.com/identity/digital-credentials#verified) (VCs) based on the user's current email from the active Google Accounts on the device. These credentials are issued to the device in advance, typically while the device is idle. While these credentials might remain valid for multiple days, the system performs a check at the moment of sharing the credentials to ensure that the account still exists, is on the device, and that the email address is valid---effectively prioritizing the account's immediate status over the credential's validity window.
-To help ensure authenticity, a Key Binding (kb) signature is generated at the
-time of sharing, incorporating the nonce.
+To help ensure authenticity, a Key Binding (kb) signature is generated at the time of sharing, incorporating the nonce.
-If a device is offline or the account is removed, the process fails rather than
-providing an expired VC or a VC for an inactive Google Account.
+If a device is offline or the account is removed, the process fails rather than providing an expired VC or a VC for an inactive Google Account.
### Email deliverability
-While the process confirms the account's legitimacy, it does not guarantee inbox
-delivery (for instance, the email might be diverted to spam). An OTP remains the
-definitive method for confirming email deliverability.
+While the process confirms the account's legitimacy, it does not guarantee inbox delivery (for instance, the email might be diverted to spam). An OTP remains the definitive method for confirming email deliverability.
## Comparison with Sign in with Google
-While both Digital Credentials and [Sign in with Google](https://developer.android.com/identity/sign-in/credential-manager-siwg) solutions provide a
-verified email, the user flows and use cases are different:
+While both Digital Credentials and [Sign in with Google](https://developer.android.com/identity/sign-in/credential-manager-siwg) solutions provide a verified email, the user flows and use cases are different:
- **Use cases**: The Credential Manager email verification flow is not exclusively used in sign up or sign in use cases, but rather can be used in any use case involving the retrieval of verified email. This could include account recovery as well.
- **Registration**: The Credential Manager flow does not require Google registration, unlike Sign in with Google.
diff --git a/identity/verified-email/references/android/identity/digital-credentials/index.md b/identity/verified-email/references/android/identity/digital-credentials/index.md
index 5f9ca67..0663d39 100644
--- a/identity/verified-email/references/android/identity/digital-credentials/index.md
+++ b/identity/verified-email/references/android/identity/digital-credentials/index.md
@@ -1,32 +1,20 @@
-Digital credentials are cryptographically verifiable documents that can be used
-to authenticate, authorize, or otherwise provide information about a user. These
-are typically things such as mobile driver's licenses, digital passports,
-boarding passes, etc. They reside in virtual containers called digital wallets,
-and are part of a W3C standard that specifies how to access and retrieve them.
-This standard is implemented for web use cases with the [W3C Credential
-Management API](https://www.w3.org/TR/credential-management-1/) and on Android, with Credential Manager's
-[DigitalCredential API](https://developer.android.com/reference/kotlin/androidx/credentials/DigitalCredential).
+Digital credentials are cryptographically verifiable documents that can be used to authenticate, authorize, or otherwise provide information about a user. These are typically things such as mobile driver's licenses, digital passports, boarding passes, etc. They reside in virtual containers called digital wallets, and are part of a W3C standard that specifies how to access and retrieve them. This standard is implemented for web use cases with the [W3C Credential Management API](https://www.w3.org/TR/credential-management-1/) and on Android, with Credential Manager's [DigitalCredential API](https://developer.android.com/reference/kotlin/androidx/credentials/DigitalCredential).
## Understand digital credentials
-In the physical world, a person might keep their identity in their wallet, and
-present it to a requesting party when asked:
+In the physical world, a person might keep their identity in their wallet, and present it to a requesting party when asked:
 **Figure 1.** The process of fulfilling a physical-world credential request. The requestor asks the user for a specific credential. Then, the user selects and retrieves it from their physical wallet. Finally, the user provides the credential to the requestor.
-In this case, a user generally has a single wallet, and retrieves the requested
-credentials from the wallet to present to the requestor. Wallets are mostly
-interchangeable, and can generally store the same things.
+In this case, a user generally has a single wallet, and retrieves the requested credentials from the wallet to present to the requestor. Wallets are mostly interchangeable, and can generally store the same things.
-Digital credentials have the following differences from credentials in the
-physical world:
+Digital credentials have the following differences from credentials in the physical world:
1. Users are expected to have multiple wallets - also known as **holders** - which can contain various different credentials. Wallets determine which credentials may be stored inside of them.
2. The app or service asking for the credential to grant access or verify an identity is called the **verifier**.
3. The entity that creates the credential and asserts claims about the subject (such as, a university, a government, or a tech company) is referred to as the **issuer**.
4. The credential presentation happens in software, which means an API surface retrieves and presents the credentials - in Android, this is Credential Manager.
-As such, Credential Manager takes on several roles that were formerly handled by
-the user:
+As such, Credential Manager takes on several roles that were formerly handled by the user:
1. On Android, wallets must register their credentials metadata with Credential Manager to be listed in the Credential Manager UI.
2. Credential Manager matches credentials across wallets based on the request and presents a list for the user to select.
@@ -37,52 +25,32 @@ This flow is shown here:
## Verifiable credentials
-Verifiable credentials are a subset of digital credentials governed by strict
-standards (like the W3C Verifiable Credentials Data Model). These credentials
-contain claims that are cryptographically secured, making them tamper-evident
-and proving exactly who issued them.
+Verifiable credentials are a subset of digital credentials governed by strict standards (like the W3C Verifiable Credentials Data Model). These credentials contain claims that are cryptographically secured, making them tamper-evident and proving exactly who issued them.
-Not all digital credentials are verifiable credentials, but all verifiable
-credentials are digital credentials.
+Not all digital credentials are verifiable credentials, but all verifiable credentials are digital credentials.
## What it means for a claim to be verified
-When a credential arrives through the Android Credential Manager API and a claim
-within it is marked as "verified," it implies that the issuer is asserting that
-they performed a check on that specific piece of data. However, it does not mean
-the data is an absolute, universal truth. "Verified" is an assertion of process,
-not an automatic guarantee of trust.
+When a credential arrives through the Android Credential Manager API and a claim within it is marked as "verified," it implies that the issuer is asserting that they performed a check on that specific piece of data. However, it does not mean the data is an absolute, universal truth. "Verified" is an assertion of process, not an automatic guarantee of trust.
-The core philosophy of this ecosystem is that trust is always resolved at the
-verifier. When the verifier (your app) receives the cryptographically secure
-data, and sees that the issuer marked it as "verified," it must determine
-whether it trusts the issuer to have verified the claim to its standards.
+The core philosophy of this ecosystem is that trust is always resolved at the verifier. When the verifier (your app) receives the cryptographically secure data, and sees that the issuer marked it as "verified," it must determine whether it trusts the issuer to have verified the claim to its standards.
### User experience
-As shown in the Android flow, the user only needs to interact once with the
-Credential Manager UI to select the appropriate credential. Here is an example
-of how the selector looks:
+As shown in the Android flow, the user only needs to interact once with the Credential Manager UI to select the appropriate credential. Here is an example of how the selector looks:
 **Figure 3.** The digital credentials UI.
### Standards
-Digital credentials requests are created using the [OpenID4VP
-standard](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html#name-introduction). You can see example requests at the [Digital
-Credentials Demo site](https://digital-credentials.dev/).
+Digital credentials requests are created using the [OpenID4VP standard](https://openid.net/specs/openid-4-verifiable-presentations-1_0.html#name-introduction). You can see example requests at the [Digital Credentials Demo site](https://digital-credentials.dev/).
-Digital credential responses are typically returned in a standardized credential
-format. These are maintained by different standards bodies, and include [W3C
-Verifiable Credentials](https://www.w3.org/TR/vc-data-model-2.0/), [sd-jwt](https://datatracker.ietf.org/doc/draft-ietf-oauth-selective-disclosure-jwt/), and
-[mdoc](https://www.iso.org/standard/69084.html).
+Digital credential responses are typically returned in a standardized credential format. These are maintained by different standards bodies, and include [W3C Verifiable Credentials](https://www.w3.org/TR/vc-data-model-2.0/), [sd-jwt](https://datatracker.ietf.org/doc/draft-ietf-oauth-selective-disclosure-jwt/), and [mdoc](https://www.iso.org/standard/69084.html).
-Custom protocols are also feasible, though we recommend using one of the
-standard protocols in your application.
+Custom protocols are also feasible, though we recommend using one of the standard protocols in your application.
### Try it out
-You can test out the digital credentials flow across platforms with an Android
-wallet and web-based verifier:
+You can test out the digital credentials flow across platforms with an Android wallet and web-based verifier:
1. Install the [CMWallet public sample](https://github.com/digitalcredentialsdev/CMWallet) on your Android phone. You can do this by pulling from the repository and installing directly from Android Studio or navigating to and selecting the latest build to access the latest `app-debug.apk` file.
2. Open the CMWallet to register the metadata with Credential Manager. Make sure Bluetooth is enabled to allow your devices to connect to each other.
diff --git a/identity/verified-email/references/android/identity/passkeys/create-passkeys.md b/identity/verified-email/references/android/identity/passkeys/create-passkeys.md
index bfe19e5..3a190a3 100644
--- a/identity/verified-email/references/android/identity/passkeys/create-passkeys.md
+++ b/identity/verified-email/references/android/identity/passkeys/create-passkeys.md
@@ -1,11 +1,6 @@
-Before your users can authenticate with passkeys, your app must first register
-or create the passkey for their account.
+Before your users can authenticate with passkeys, your app must first register or create the passkey for their account.
-To create the passkey, obtain details required to create the passkey from your
-app server, and then call the Credential Manager API, which returns a public and
-private key pair. The returned private key is stored in a credential provider,
-such as Google Password Manager, as a passkey. The public key is stored on your
-app server.
+To create the passkey, obtain details required to create the passkey from your app server, and then call the Credential Manager API, which returns a public and private key pair. The returned private key is stored in a credential provider, such as Google Password Manager, as a passkey. The public key is stored on your app server.
> [!TIP]
> **Tip:** While designing authentication flows with passkeys, make sure that you follow the [UX guidelines for passkeys](https://developer.android.com/design/ui/mobile/guides/patterns/passkeys).
@@ -14,15 +9,11 @@ app server.
## Prerequisites
-Make sure that you have set up [Digital Asset Links](https://developer.android.com/identity/credential-manager/prerequisites) and that you target
-devices running Android 9 (API level 28) or higher.
+Make sure that you have set up [Digital Asset Links](https://developer.android.com/identity/credential-manager/prerequisites) and that you target devices running Android 9 (API level 28) or higher.
## Overview
-This guide focuses on the changes required in your [relying party client app](https://developer.android.com/identity/credential-manager#authentication-terminology)
-to create a passkey, and gives a brief overview of the [relying party app
-server](https://developer.android.com/identity/credential-manager#authentication-terminology) implementation. To learn more about the server-side integration, see
-[Server-side passkey registration](https://developers.google.com/identity/passkeys/developer-guides/server-registration).
+This guide focuses on the changes required in your [relying party client app](https://developer.android.com/identity/credential-manager#authentication-terminology) to create a passkey, and gives a brief overview of the [relying party app server](https://developer.android.com/identity/credential-manager#authentication-terminology) implementation. To learn more about the server-side integration, see [Server-side passkey registration](https://developers.google.com/identity/passkeys/developer-guides/server-registration).
1. [**Add dependencies to your app**](https://developer.android.com/identity/passkeys/create-passkeys#add-dependencies): Add the required Credential Manager libraries.
2. [**Instantiate Credential Manager**](https://developer.android.com/identity/passkeys/create-passkeys#instantiate): Create a Credential Manager instance.
@@ -33,8 +24,7 @@ server](https://developer.android.com/identity/credential-manager#authentication
7. [**Notify the user**](https://developer.android.com/identity/passkeys/create-passkeys#notify): Notify the user that their passkey has been created.
> [!TIP]
-> **Tip:** To enhance the user experience during sign up, add functionality to [restore credentials](https://developer.android.com/identity/sign-in/restore-credentials) on a new device to let users seamlessly set up their existing accounts on new Android devices, and [suppressing autofill dialogs on
-> credential fields](https://developer.android.com/identity/passkeys/create-passkeys#suppress-autofill).
+> **Tip:** To enhance the user experience during sign up, add functionality to [restore credentials](https://developer.android.com/identity/sign-in/restore-credentials) on a new device to let users seamlessly set up their existing accounts on new Android devices, and [suppressing autofill dialogs on credential fields](https://developer.android.com/identity/passkeys/create-passkeys#suppress-autofill).
## Add dependencies to your app
@@ -44,8 +34,8 @@ Add the following dependencies to your app module's `build.gradle` file:
```kotlin
dependencies {
- implementation("androidx.credentials:credentials:1.7.0-alpha02")
- implementation("androidx.credentials:credentials-play-services-auth:1.7.0-alpha02")
+ implementation("androidx.credentials:credentials:1.7.0-alpha03")
+ implementation("androidx.credentials:credentials-play-services-auth:1.7.0-alpha03")
}
```
@@ -53,8 +43,8 @@ dependencies {
```groovy
dependencies {
- implementation "androidx.credentials:credentials:1.7.0-alpha02"
- implementation "androidx.credentials:credentials-play-services-auth:1.7.0-alpha02"
+ implementation "androidx.credentials:credentials:1.7.0-alpha03"
+ implementation "androidx.credentials:credentials-play-services-auth:1.7.0-alpha03"
}
```
@@ -71,26 +61,16 @@ Use your app or activity context to create a `CredentialManager` object.
## Get credential creation options from your app server
-When the user clicks a "Create Passkey" button or when a new user signs up, make
-a request from your app to your app server to obtain the information required to
-start the passkey registration process.
+When the user clicks a "Create Passkey" button or when a new user signs up, make a request from your app to your app server to obtain the information required to start the passkey registration process.
-Use a FIDO-compliant library in your app server to send your client app the
-information required to create a passkey, such as information about the user,
-the app, and additional configuration properties. To learn more, see [Server
-side passkey registration](https://developers.google.com/identity/passkeys/developer-guides/server-registration).
+Use a FIDO-compliant library in your app server to send your client app the information required to create a passkey, such as information about the user, the app, and additional configuration properties. To learn more, see [Server side passkey registration](https://developers.google.com/identity/passkeys/developer-guides/server-registration).
-In the client app, decode the public key creation options sent by the app
-server. These are usually represented in JSON format. To learn more about how
-this decoding is done for web clients, see [Encoding and
-Decoding](https://developers.google.com/identity/passkeys/developer-guides/server-registration#encoding_and_decoding). For Android client apps, you must handle the decoding
-separately.
+In the client app, decode the public key creation options sent by the app server. These are usually represented in JSON format. To learn more about how this decoding is done for web clients, see [Encoding and Decoding](https://developers.google.com/identity/passkeys/developer-guides/server-registration#encoding_and_decoding). For Android client apps, you must handle the decoding separately.
> [!NOTE]
> **Note:** On your app server, securely store the `challenge` so that you can later verify the origin of the credential.
-The following snippet shows the structure the public key creation options sent
-by the app server:
+The following snippet shows the structure the public key creation options sent by the app server:
{
"challenge": "",
@@ -149,9 +129,7 @@ Key fields in the public key creation options include:
## Create a passkey
-After you have parsed the server-side public key creation options, create a
-passkey by wrapping these options in a `CreatePublicKeyCredentialRequest` object
-and calling `createCredential()`.
+After you have parsed the server-side public key creation options, create a passkey by wrapping these options in a `CreatePublicKeyCredentialRequest` object and calling `createCredential()`.
The `createPublicKeyCredentialRequest` includes the following:
@@ -160,25 +138,14 @@ The `createPublicKeyCredentialRequest` includes the following:
- `false` (default): Use this value if the call to Credential Manager was triggered by an explicit user action.
- `true`: Use this value if Credential Manager is opportunistically called, such as when first opening the app.
If you set the value to `true` and there are no immediately available credentials, Credential Manager won't show any UI and the request will fail immediately, returning NoCredentialException for get requests and [`CreateCredentialNoCreateOptionException`](https://developer.android.com/reference/kotlin/androidx/credentials/exceptions/CreateCredentialNoCreateOptionException) for create requests.
-- `origin`: This field is automatically set for Android apps. For browsers and similarly privileged apps that need to set `origin`, see [Make Credential
- Manager calls on behalf of other parties for privileged apps](https://developer.android.com/training/sign-in/privileged-apps).
+- `origin`: This field is automatically set for Android apps. For browsers and similarly privileged apps that need to set `origin`, see [Make Credential Manager calls on behalf of other parties for privileged apps](https://developer.android.com/training/sign-in/privileged-apps).
- `isConditional`: This is an optional field that defaults to `false`. For more information, see [Automatically create a passkey](https://developer.android.com/identity/passkeys/create-passkeys#automatic-upgrade).
-Calling the `createCredential()` function launches Credential Manager's built-in
-bottom sheet UI that prompts the user to use a passkey and to select a
-credential provider and account for storage. However, if `isConditional` is set
-to `true`, the bottom sheet UI does not display, and the passkey is
-automatically created.
+Calling the `createCredential()` function launches Credential Manager's built-in bottom sheet UI that prompts the user to use a passkey and to select a credential provider and account for storage. However, if `isConditional` is set to `true`, the bottom sheet UI does not display, and the passkey is automatically created.
### Automatically create a passkey
-You can automatically create a passkey for a user after a successful password
-login by setting the `isConditional` parameter to `true` in your
-`CreatePublicKeyCredentialRequest` while creating a passkey. If the user doesn't
-already have a passkey, your app will automatically attempt to create one in the
-background and store it in the user's credential provider, such as Google
-Password Manager. For an example of how this is implemented, see the [public
-sample](https://github.com/android/identity-samples/blob/main/Shrine/app/src/main/java/com/authentication/shrine/ui/AuthenticationScreen.kt#L98).
+You can automatically create a passkey for a user after a successful password login by setting the `isConditional` parameter to `true` in your `CreatePublicKeyCredentialRequest` while creating a passkey. If the user doesn't already have a passkey, your app will automatically attempt to create one in the background and store it in the user's credential provider, such as Google Password Manager. For an example of how this is implemented, see the [public sample](https://github.com/android/identity-samples/blob/main/Shrine/app/src/main/java/com/authentication/shrine/ui/AuthenticationScreen.kt#L98).
 **Figure 2:**Google Password Manager notification
> [!NOTE]
@@ -186,11 +153,9 @@ sample](https://github.com/android/identity-samples/blob/main/Shrine/app/src/mai
## Handle the response
-After the user is verified using the device's screen lock, a passkey is created
-and stored in the user's selected credential provider.
+After the user is verified using the device's screen lock, a passkey is created and stored in the user's selected credential provider.
-The response after you successfully call `createCredential()` is a
-[PublicKeyCredential](https://developer.android.com/jetpack/androidx/releases/credentials) object.
+The response after you successfully call `createCredential()` is a [PublicKeyCredential](https://developer.android.com/jetpack/androidx/releases/credentials) object.
The `PublicKeyCredential` looks as follows:
@@ -241,79 +206,55 @@ Add code to handle failures as shown in the following snippet:
## Verify and save the public key on the app server
-On the app server, you must verify the public key credential and then [save the
-public key](https://web.dev/articles/passkey-registration#save-credential).
+On the app server, you must verify the public key credential and then [save the public key](https://web.dev/articles/passkey-registration#save-credential).
-To verify the public key credential's origin, compare it against an allow list
-of approved apps. If a key has an unrecognized origin, reject it.
+To verify the public key credential's origin, compare it against an allow list of approved apps. If a key has an unrecognized origin, reject it.
> [!NOTE]
> **Note:** An app's origin is based on its unique identity, which is the SHA-256 fingerprint of its signing certificate.
To obtain the app's SHA 256 fingerprint:
-1. Print your release app's signing certificate by running the following
- command in a terminal:
+1. Print your release app's signing certificate by running the following command in a terminal:
keytool -list -keystore
- In the response, identify the signing certificate's SHA 256 fingerprint,
- mentioned as `Certificate fingerprints block` : `SHA256`.
-2. Encode the SHA256 fingerprint with base64url encoding. This Python example
- demonstrates how to properly encode the fingerprint:
+ In the response, identify the signing certificate's SHA 256 fingerprint, mentioned as `Certificate fingerprints block` : `SHA256`.
+2. Encode the SHA256 fingerprint with base64url encoding. This Python example demonstrates how to properly encode the fingerprint:
import binascii
import base64
fingerprint = '' # your app's SHA256 fingerprint
print(base64.urlsafe_b64encode(binascii.a2b_hex(fingerprint.replace(':', ''))).decode('utf8').replace('=', ''))
-3. Append `android:apk-key-hash`: to the start of the output from the previous
- step so that you get something that is similar to the following:
+3. Append `android:apk-key-hash`: to the start of the output from the previous step so that you get something that is similar to the following:
android:apk-key-hash:
- The result should match with an allowed origin on your app server. If you
- have multiple signing certificates, such as certificates for debugging and
- release, or multiple apps, then repeat the process and accept all the
- origins as valid on the app server.
+ The result should match with an allowed origin on your app server. If you have multiple signing certificates, such as certificates for debugging and release, or multiple apps, then repeat the process and accept all the origins as valid on the app server.
> [!NOTE]
> **Note:** When you save the passkey on the app server, make sure that you save the Authenticator Attestation Globally Unique Identifier ([AAGUID](https://web.dev/articles/webauthn-aaguid)) from the client data. The AAGUID is a unique number that identifies the model of the authenticator. For more information, see [Manage passkeys](https://developer.android.com/identity/passkeys/manage-passkeys).
## Notify the user
-After the passkey is successfully created, notify your users about the passkey
-and inform them that they can manage their passkeys from their credential
-provider app or from [within the app settings](https://developer.android.com/identity/passkeys/manage-passkeys). Notify users by using a
-custom dialog, notification, or snackbar. Since an unexpected passkey creation
-by a malicious entity requires an immediate security alert, consider
-supplementing these in-app methods with external communication, such as an
-email.
+After the passkey is successfully created, notify your users about the passkey and inform them that they can manage their passkeys from their credential provider app or from [within the app settings](https://developer.android.com/identity/passkeys/manage-passkeys). Notify users by using a custom dialog, notification, or snackbar. Since an unexpected passkey creation by a malicious entity requires an immediate security alert, consider supplementing these in-app methods with external communication, such as an email.
## Enhance the user experience
-To enhance the user experience while implementing sign up with Credential
-Manager, consider adding functionality for restore credentials and suppress
-autofill dialogs.
+To enhance the user experience while implementing sign up with Credential Manager, consider adding functionality for restore credentials and suppress autofill dialogs.
### Add functionality to restore credentials on a new device
-To allow users to seamlessly log into their accounts on a new device, implement
-the [Restore Credentials](https://developer.android.com/identity/sign-in/restore-credentials) functionality. Adding restore credentials with
-`BackupAgent` logs users in when they open your restored app on a new device,
-letting them use your app right away.
+To allow users to seamlessly log into their accounts on a new device, implement the [Restore Credentials](https://developer.android.com/identity/sign-in/restore-credentials) functionality. Adding restore credentials with `BackupAgent` logs users in when they open your restored app on a new device, letting them use your app right away.
### Suppress autofill on credential fields (optional)
-For app screens where users are expected to use Credential Manager's bottom
-sheet UI for authentication, add the `isCredential` attribute to the username
-and password fields. This suppresses autofill dialogs (`FillDialog` and
-`SaveDialog`) from overlapping with Credential Manager's bottom sheet UI.
+For app screens where users are expected to use Credential Manager's bottom sheet UI for authentication, add the `isCredential` attribute to the username and password fields. This suppresses autofill dialogs (`FillDialog` and `SaveDialog`) from overlapping with Credential Manager's bottom sheet UI.
The `isCredential` attribute is supported on Android 14 and higher.
-The following example demonstrates how you can add the `isCredential` attribute
-to the relevant username and password fields in the relevant views for your app:
+The following example demonstrates how you can add the `isCredential` attribute to the relevant username and password fields in the relevant views for your app:
```kotlin
@Preview(name = "Phone", device = Devices.PHONE, showBackground = true)
@@ -64,25 +61,21 @@ fun FeedScreenPreview() {
}
}
}
+
```
## Step 2. Make the navigation bar adaptive
-Bottom navigation bars are optimized for touch input when the user is holding a
-phone in portrait mode. On larger screen hand-held devices, like tablets and
-unfolded foldables, the navigation area must be accessible from the edge of the
-screen (navigation rail).
+Bottom navigation bars are optimized for touch input when the user is holding a phone in portrait mode. On larger screen hand-held devices, like tablets and unfolded foldables, the navigation area must be accessible from the edge of the screen (navigation rail).
-If you need to provide more screen space for the content, hide the
-navigation area. Examples of this include:
+If you need to provide more screen space for the content, hide the navigation area. Examples of this include:
- Hiding the navigation bar when the user scrolls down and showing it again when the user scrolls up. The assumption is that when the user is scrolling down, they are consuming content but when scrolling up they are trying to navigate away from that content.
- Hiding the navigation area when its content is distracting. For example, in camera previews or when displaying a full-screen photo.
-When the detail screen is displayed full-screen on mobile, full-screen mode must
-be deactivated on larger screens.
+When the detail screen is displayed full-screen on mobile, full-screen mode must be deactivated on larger screens.
Steps to migrate:
@@ -94,10 +87,7 @@ Steps to migrate:
### Step 2.1. Control navigation area visibility
-If the navigation bar's visibility changes - it is hidden under certain
-scenarios or on certain screens - this behavior must be maintained with the
-adaptive navigation area. This is done using `NavigationSuiteScaffold`'s `state`
-parameter.
+If the navigation bar's visibility changes - it is hidden under certain scenarios or on certain screens - this behavior must be maintained with the adaptive navigation area. This is done using `NavigationSuiteScaffold`'s `state` parameter.
Steps to migrate:
@@ -107,6 +97,7 @@ Steps to migrate:
For example:
+
```kotlin
// Pass this variable to any composable that needs to control the navigation area visibility
@@ -127,33 +118,26 @@ LaunchedEffect(isNavBarVisible){
scaffoldVisibilityState.hide()
}
}
+
```
## Step 3. Add multi-pane layouts using Navigation 3 Scenes
-Analyze the codebase looking for related screens - tapping on something in one
-screen opens another screen that shows information related to the first. There
-are two canonical screen relationships: list-detail and supporting pane.
+Analyze the codebase looking for related screens - tapping on something in one screen opens another screen that shows information related to the first. There are two canonical screen relationships: list-detail and supporting pane.
-IMPORTANT: You must use the Navigation 3 `SceneStrategy` approach to implement
-multi-pane layouts. Do not use `ListDetailPaneScaffold` or
-`SupportingPaneScaffold`.
+IMPORTANT: You must use the Navigation 3 `SceneStrategy` approach to implement multi-pane layouts. Do not use `ListDetailPaneScaffold` or `SupportingPaneScaffold`.
### Step 3.1. List-detail
#### Identify the list and detail screens
-List-detail layouts display a list of items (this is the list screen) and
-clicking on an item opens a new screen that shows more details about that item
-(the detail screen).
+List-detail layouts display a list of items (this is the list screen) and clicking on an item opens a new screen that shows more details about that item (the detail screen).
Typical usage includes productivity apps like email, notes, and messaging.
-Unless requested explicitly, avoid this pattern when the detail content requires
-substantial screen space (e.g., images or media that benefits from a full-screen
-presentation).
+Unless requested explicitly, avoid this pattern when the detail content requires substantial screen space (e.g., images or media that benefits from a full-screen presentation).
#### Add a Material list-detail SceneStrategy
@@ -163,8 +147,7 @@ presentation).
#### Use metadata to identify the list and detail screens
-- Add metadata using `entry(metadata = ...)` or `NavEntry(metadata = ...)` to the list entry using `ListDetailSceneStrategy.listPane(detailPlaceholder = {
- })`.
+- Add metadata using `entry(metadata = ...)` or `NavEntry(metadata = ...)` to the list entry using `ListDetailSceneStrategy.listPane(detailPlaceholder = { })`.
- Use the `detailPlaceholder` parameter to add a placeholder on the detail screen when no list items are selected.
- Add metadata to the detail entry using `ListDetailSceneStrategy.detailPane()`.
@@ -173,14 +156,11 @@ presentation).
- When a detail screen displays its content full-screen on mobile (content fills the entire screen, bars or rails are hidden), full-screen mode must be deactivated if it's part of a list-detail layout.
- Detail screens must not show a back arrow when on a list-detail layout.
-For a reference implementation, check the [Nav3 **Material** List Detail
-recipe](references/android/guide/navigation/navigation-3/recipes/material-listdetail.md).
+For a reference implementation, check the [Nav3 **Material** List Detail recipe](references/android/guide/navigation/navigation-3/recipes/material-listdetail.md).
### Step 3.2. Supporting pane
-Identify supporting pane screens where a main screen displays a single item, and
-selecting it opens a "supporting screen" with more details. The supporting
-screen complements the main screen and is shown in a supporting pane.
+Identify supporting pane screens where a main screen displays a single item, and selecting it opens a "supporting screen" with more details. The supporting screen complements the main screen and is shown in a supporting pane.
#### Add a Material supporting pane `SceneStrategy`
@@ -195,15 +175,13 @@ screen complements the main screen and is shown in a supporting pane.
### Step 3.3. Run screenshot tests
-If you have made changes, record new reference files. Ask the user to visually
-verify that the new layouts are correct.
+If you have made changes, record new reference files. Ask the user to visually verify that the new layouts are correct.
## Step 4. Make vertical lists adaptive by changing the number of columns
### Step 4.1. Make lazy lists adaptive
-Look for the following vertical list composables: `LazyColumn`,
-`LazyVerticalGrid`, `LazyVerticalStaggeredGrid`.
+Look for the following vertical list composables: `LazyColumn`, `LazyVerticalGrid`, `LazyVerticalStaggeredGrid`.
Steps to migrate:
@@ -214,24 +192,16 @@ Steps to migrate:
### Step 4.2. Migrate non-lazy lists to Grid
-WARNING: Grid is an experimental API available from Compose 1.11.0-beta01.
-Confirm with the user that they are happy to use an experimental API in their
-codebase.
+WARNING: Grid is an experimental API available from Compose 1.11.0-beta01. Confirm with the user that they are happy to use an experimental API in their codebase.
-Look for any `Column` that contains multiple items of the same type and replace
-it with `Grid`. Do not replace it with `LazyVerticalGrid` or any other lazy
-layout. Do not place `Grid` inside the existing `Column`. Completely replace it.
+Look for any `Column` that contains multiple items of the same type and replace it with `Grid`. Do not replace it with `LazyVerticalGrid` or any other lazy layout. Do not place `Grid` inside the existing `Column`. Completely replace it.
-`Grid` is configured by supplying a lambda (an extension function on
-`GridConfigurationScope`) to its `config` parameter. Inside the lambda,
-`constraints` provides the minimum and maximum dimensions of the grid container
-and can be used to change the number of rows and columns based on the available
-size. For example, the following code configures `Grid` such that when the
-available width is:
+`Grid` is configured by supplying a lambda (an extension function on `GridConfigurationScope`) to its `config` parameter. Inside the lambda, `constraints` provides the minimum and maximum dimensions of the grid container and can be used to change the number of rows and columns based on the available size. For example, the following code configures `Grid` such that when the available width is:
- less than 800dp, a 2x4 grid is used
- 800dp or more, a 4x2 grid is used
+
```kotlin
Grid(
@@ -250,26 +220,23 @@ Grid(
gap(gapSizeDp)
}
) { /** items **/ }
+
```
-`Grid` is an experimental API so add the `@OptIn(ExperimentalGridApi::class)`
-annotation to any function that uses it.
+`Grid` is an experimental API so add the `@OptIn(ExperimentalGridApi::class)` annotation to any function that uses it.
## Step 5: Hide App Bars when scrolling
-In an app with multiple top-level destinations, each screen must manage its own
-app bar state independently. There are two main scroll behaviors:
+In an app with multiple top-level destinations, each screen must manage its own app bar state independently. There are two main scroll behaviors:
- `exitUntilCollapsedScrollBehavior`: Hides on scroll down, stays hidden while you scroll up until you reach the very top (0 offset).
- `enterAlwaysScrollBehavior`: Hides on scroll down, shows immediately on scroll up.
## Final step: Build and test
-Build the app and run the local tests. If the project has screenshot tests, run
-them but DO NOT update the reference images. Prompt the user to do this after
-they have viewed the screenshot diffs.
+Build the app and run the local tests. If the project has screenshot tests, run them but DO NOT update the reference images. Prompt the user to do this after they have viewed the screenshot diffs.
## Additional documentation for experimental adaptive APIs
@@ -286,14 +253,11 @@ Check the FlexBox documentation:
## MediaQuery
-Check the [MediaQuery documentation](references/android/develop/ui/compose/layouts/adaptive/mediaquery/index.md) when you need to query the device's
-screen size, pointer precision, keyboard type, whether it has cameras or
-microphones, and other device capabilities.
+Check the [MediaQuery documentation](references/android/develop/ui/compose/layouts/adaptive/mediaquery/index.md) when you need to query the device's screen size, pointer precision, keyboard type, whether it has cameras or microphones, and other device capabilities.
## Grid
-Check the Grid documentation when you need to display a fixed number of items in
-a grid layout:
+Check the Grid documentation when you need to display a fixed number of items in a grid layout:
- [Overview](references/android/develop/ui/compose/layouts/adaptive/grid/index.md)
- [Get started - setup](references/android/develop/ui/compose/layouts/adaptive/grid/get-started.md)
diff --git a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/container-behavior.md b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/container-behavior.md
index 41112fc..27c2e3d 100644
--- a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/container-behavior.md
+++ b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/container-behavior.md
@@ -1,6 +1,6 @@
-To configure the behavior of the `FlexBox` container, create a `FlexBoxConfig`
-block and supply it using the `config` parameter.
+To configure the behavior of the `FlexBox` container, create a `FlexBoxConfig` block and supply it using the `config` parameter.
+
```kotlin
FlexBox(
@@ -14,17 +14,16 @@ FlexBox(
}
) { // child items
}
+
```
-Use `FlexBoxConfig` to define the layout direction, wrapping behavior,
-alignment, and gaps between items.
+Use `FlexBoxConfig` to define the layout direction, wrapping behavior, alignment, and gaps between items.
## Layout direction
-The `direction` function sets the main axis, which dictates the direction
-items are laid out in. It accepts the following values:
+The `direction` function sets the main axis, which dictates the direction items are laid out in. It accepts the following values:
- `Row` (default): Sets the main axis to be horizontal. In left-to-right locales this will be left-to-right, with the opposite in right-to-left.
- `RowReverse`: Reverses the direction of `Row`.
@@ -33,13 +32,11 @@ items are laid out in. It accepts the following values:
## Align items and distribute extra space
-The following sections describe how to align items and distribute extra space
-along the main and cross axes.
+The following sections describe how to align items and distribute extra space along the main and cross axes.
### Along the main axis
-Use `justifyContent` to distribute items along the main axis. The following
-table shows the behavior when the direction is `Row`.
+Use `justifyContent` to distribute items along the main axis. The following table shows the behavior when the direction is `Row`.
|---|---|
| |  |
@@ -52,9 +49,7 @@ table shows the behavior when the direction is `Row`.
### Along the cross axis
-Use `alignItems` to align items along the cross axis within a single line. This
-behavior can be overridden by individual items using the
-[`alignSelf` modifier](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/item-behavior#item-alignment).
+Use `alignItems` to align items along the cross axis within a single line. This behavior can be overridden by individual items using the [`alignSelf` modifier](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/item-behavior#item-alignment).
The following images show the behavior when the direction is `Row`:
@@ -62,10 +57,7 @@ The following images show the behavior when the direction is `Row`:
|  |  |  |  |  |  |
| | `Start` | `End` | `Center` | `Stretch` | `Baseline` |
-Use `alignContent` to align lines to the cross axis and to distribute extra
-space between lines. This property only applies when there are multiple lines
-(wrapping is enabled). The following images show the behavior when the direction
-is `Row`:
+Use `alignContent` to align lines to the cross axis and to distribute extra space between lines. This property only applies when there are multiple lines (wrapping is enabled). The following images show the behavior when the direction is `Row`:
|---|---|---|---|---|---|---|
|  |  |  |  |  |  |  |
@@ -73,9 +65,7 @@ is `Row`:
## Wrap items
-Wrapping lets a `FlexBox` container become multi-line, moving items that don't
-fit onto a new row or column along the cross-axis. Configure wrapping behavior
-using `wrap`.
+Wrapping lets a `FlexBox` container become multi-line, moving items that don't fit onto a new row or column along the cross-axis. Configure wrapping behavior using `wrap`.
|---|---|
| **`FlexWrap` value** | **Example using direction `Row`** |
@@ -83,29 +73,20 @@ using `wrap`.
| `Wrap`: When there is insufficient space for an item (plus any [gap](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior#add-gaps)), a new line is created in the direction of the cross axis. For example, if the direction is `Row`, a new line is added **below**. |  |
| `WrapReverse`: The same as `Wrap`, except the new line is added in the opposite direction to the cross axis. For example, if the direction is `Row`, a new line is added **above**. |  |
-The following example shows how the `FlexBox` wrapping algorithm works. The
-`FlexBox` container has a main size of `100dp`, with `wrap` set to
-`FlexWrap.Wrap` and a gap of `8dp`. It contains three items with `basis` `20dp`,
-`40dp`, and `50dp`, respectively.
+The following example shows how the `FlexBox` wrapping algorithm works. The `FlexBox` container has a main size of `100dp`, with `wrap` set to `FlexWrap.Wrap` and a gap of `8dp`. It contains three items with `basis` `20dp`, `40dp`, and `50dp`, respectively.
-There is `100dp` available space in the line. Child 1 is `20dp`.
-There is space, so Child 1 is placed into the line.
+There is `100dp` available space in the line. Child 1 is `20dp`. There is space, so Child 1 is placed into the line.
 **Figure 1.** First item placed in the `FlexBox` container.
-There is `80dp` available space in the line. The gap is `8dp`. Child 2 is
-`40dp`. The required space is `48dp`. There is space, so the gap and Child 2
-are placed into the line.
+There is `80dp` available space in the line. The gap is `8dp`. Child 2 is `40dp`. The required space is `48dp`. There is space, so the gap and Child 2 are placed into the line.
 **Figure 2.** Second item placed in the `FlexBox` container after the first item.
-There is `32dp` available space in the line. The gap is `8dp`. Child 3 is
-`50dp`. The required space is `58dp`. There is not enough space in the current
-line, so Child 3 is placed in a new line.
+There is `32dp` available space in the line. The gap is `8dp`. Child 3 is `50dp`. The required space is `58dp`. There is not enough space in the current line, so Child 3 is placed in a new line.
 **Figure 3.** Third item placed on a new line because it doesn't fit on the first line.
## Add gaps between items
-Add gaps between rows and columns using `rowGap` and `columnGap`. This is useful
-to avoid adding spacing modifiers to children.
+Add gaps between rows and columns using `rowGap` and `columnGap`. This is useful to avoid adding spacing modifiers to children.
|---|---|---|
|  |  |  |
diff --git a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/get-started.md b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/get-started.md
index 8b00b01..2bf41f0 100644
--- a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/get-started.md
+++ b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/get-started.md
@@ -2,11 +2,10 @@ This page describes how to implement basic `FlexBox` layouts.
## Set up project
-1. Add the [`androidx.compose.foundation.layout`](https://developer.android.com/jetpack/androidx/versions) library to your project's
- `lib.versions.toml`.
+1. Add the [`androidx.compose.foundation.layout`](https://developer.android.com/jetpack/androidx/versions) library to your project's `lib.versions.toml`.
[versions]
- compose = "1.12.0-beta02"
+ compose = "1.12.0-rc01"
[libraries]
androidx-compose-foundation-layout = { group = "androidx.compose.foundation", name = "foundation-layout", version.ref = "compose" }
@@ -19,9 +18,9 @@ This page describes how to implement basic `FlexBox` layouts.
## Create basic FlexBox layouts
-**Example 1** : `FlexBox` lays out two `Text` elements that are centrally
-aligned.
+**Example 1** : `FlexBox` lays out two `Text` elements that are centrally aligned.
+
```kotlin
FlexBox(
@@ -33,16 +32,16 @@ FlexBox(
Text(text = "Hello", fontSize = 48.sp)
Text(text = "World!", fontSize = 48.sp)
}
+
```

-**Example 2** : `FlexBox` wraps five items onto two rows and grows them unequally
-to fill the available space on each row. There is an `8.dp`
-gap, both vertically and horizontally, between the items.
+**Example 2** : `FlexBox` wraps five items onto two rows and grows them unequally to fill the available space on each row. There is an `8.dp` gap, both vertically and horizontally, between the items.
+
```kotlin
FlexBox(
@@ -59,11 +58,11 @@ FlexBox(
OrangeRoundedBox(modifier = Modifier.flex { grow(1.0f) })
PinkRoundedBox(modifier = Modifier.flex { grow(1.0f) })
}
+
```

-To learn more about `FlexBox` behavior, see [Set container behavior](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior) and [Set
-item behavior](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/item-behavior).
\ No newline at end of file
+To learn more about `FlexBox` behavior, see [Set container behavior](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior) and [Set item behavior](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/item-behavior).
\ No newline at end of file
diff --git a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/index.md b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/index.md
index ddda0de..50828f0 100644
--- a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/index.md
+++ b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/index.md
@@ -1,10 +1,7 @@
> [!NOTE]
> **Note:** FlexBox is an experimental API and is likely to change in the future. To use it, annotate your code with `@ExperimentalFlexBoxApi`. Please file any issues or feedback on the [issue tracker](https://issuetracker.google.com/issues/new?component=1876021&title=%5BFlexBox%5D).
-[`FlexBox`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/FlexBox.composable#FlexBox(androidx.compose.ui.Modifier,androidx.compose.foundation.layout.FlexBoxConfig,kotlin.Function1)) is a container that lays out items in a single direction. It can
-resize, wrap, align, and distribute space among items to optimally fill the
-available space. It's a useful layout for different sized items and for resizing
-items when the available space changes.
+[`FlexBox`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/FlexBox.composable#FlexBox(androidx.compose.ui.Modifier,androidx.compose.foundation.layout.FlexBoxConfig,kotlin.Function1)) is a container that lays out items in a single direction. It can resize, wrap, align, and distribute space among items to optimally fill the available space. It's a useful layout for different sized items and for resizing items when the available space changes.
With `FlexBox`, you can:
@@ -14,23 +11,16 @@ With `FlexBox`, you can:
## When to use FlexBox
-`FlexBox` is usually used to display a small number of items *within* an
-overall screen layout. For an overall screen layout,
-`Grid` is usually a better choice. `FlexBox` does not support lazy-loading of
-items. To display large numbers of items, use [lazy lists and grids](https://developer.android.com/develop/ui/compose/lists). If you
-need to wrap items, use `FlexBox` instead of `FlowRow` and `FlowColumn`.
+`FlexBox` is usually used to display a small number of items *within* an overall screen layout. For an overall screen layout, `Grid` is usually a better choice. `FlexBox` does not support lazy-loading of items. To display large numbers of items, use [lazy lists and grids](https://developer.android.com/develop/ui/compose/lists). If you need to wrap items, use `FlexBox` instead of `FlowRow` and `FlowColumn`.
## Terminology and concepts
> [!IMPORTANT]
> **Key Point:** `FlexBox` is heavily influenced by the [CSS Flexible Box Layout specification](https://www.w3.org/TR/css-flexbox-1/) and has almost identical concepts, terminology, and behavior. If you're familiar with `display: flex`, you'll find `FlexBox`'s properties and behavior almost identical.
-`FlexBox` lays out its items in either horizontal or vertical *lines* . This
-direction of these lines establishes the *main axis* . 90 degrees to the main
-axis is the *cross axis* . The length of the `FlexBox` along the main axis is
-known as the *main size* . The corresponding cross axis length is known as the
-*cross size* . These sizes and axes form the basis of `FlexBox`'s behavior.
+`FlexBox` lays out its items in either horizontal or vertical *lines* . This direction of these lines establishes the *main axis* . 90 degrees to the main axis is the *cross axis* . The length of the `FlexBox` along the main axis is known as the *main size* . The corresponding cross axis length is known as the *cross size* . These sizes and axes form the basis of `FlexBox`'s behavior.
+
 **Figure 1.** Axes and sizes when the `FlexBox` direction is `Row`.  **Figure 2.** Axes and sizes when the `FlexBox` direction is `Column`.
@@ -49,33 +39,18 @@ You can apply `FlexBox` properties in two ways:
### Understand the `FlexBox` layout algorithm
-One of `FlexBox`'s most powerful features is its ability to resize its children
-to best fit the space available to it. Understanding how `FlexBox` does this can
-help you set `FlexBox` properties to optimize your UI for all possible sizes.
+One of `FlexBox`'s most powerful features is its ability to resize its children to best fit the space available to it. Understanding how `FlexBox` does this can help you set `FlexBox` properties to optimize your UI for all possible sizes.
`FlexBox`'s layout algorithm works in the following way:
-1. **Calculate child base size** : Use the child's [`basis` value](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/item-behavior#set-initial-size)
- to calculate its initial size along the main axis before any extra space is
- distributed.
+1. **Calculate child base size** : Use the child's [`basis` value](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/item-behavior#set-initial-size) to calculate its initial size along the main axis before any extra space is distributed.
-2. **Sort the children** : Sort the children by their [`order`](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/item-behavior#item-order) values, if
- present.
+2. **Sort the children** : Sort the children by their [`order`](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/item-behavior#item-order) values, if present.
-3. **Build lines** : For each child, check if its initial size plus
- [`gap`](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior#add-gaps) will fit into the remaining space on the current line.
- If so, place this child into the line. If not, place it onto a new line if
- [wrapping is enabled](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior#wrap-items), or place the item into the current line
- where it will overflow (it will be partially obscured by the edge of the
- container).
+3. **Build lines** : For each child, check if its initial size plus [`gap`](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior#add-gaps) will fit into the remaining space on the current line. If so, place this child into the line. If not, place it onto a new line if [wrapping is enabled](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior#wrap-items), or place the item into the current line where it will overflow (it will be partially obscured by the edge of the container).
-4. **Align or resize items in the main axis** : For each line, distribute extra
- space *to* or between items by [resizing](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/item-behavior#item-size) or
- [aligning](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior#main-axis) them.
+4. **Align or resize items in the main axis** : For each line, distribute extra space *to* or between items by [resizing](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/item-behavior#item-size) or [aligning](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior#main-axis) them.
-5. **Align or resize items in the cross axis** : For each line, distribute extra
- space to or between items and lines by [stretching or aligning
- them](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior#cross-axis).
+5. **Align or resize items in the cross axis** : For each line, distribute extra space to or between items and lines by [stretching or aligning them](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior#cross-axis).
-Now that you're familiar with `FlexBox` concepts, see [Get started](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/get-started) to
-create a basic `FlexBox`.
\ No newline at end of file
+Now that you're familiar with `FlexBox` concepts, see [Get started](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/get-started) to create a basic `FlexBox`.
\ No newline at end of file
diff --git a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/item-behavior.md b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/item-behavior.md
index e4a5c0f..ddb0f02 100644
--- a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/item-behavior.md
+++ b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/flexbox/item-behavior.md
@@ -1,10 +1,10 @@
-Use `Modifier.flex` to control how an item changes size, order, and is aligned
-inside a `FlexBox`.
+Use `Modifier.flex` to control how an item changes size, order, and is aligned inside a `FlexBox`.
## Item size
Use the `basis`, `grow`, and `shrink` functions to control an item's size.
+
```kotlin
FlexBox {
@@ -16,14 +16,14 @@ FlexBox {
}
)
}
+
```
### Set initial size
-Use `basis` to specify the item's initial size before any extra space is
-distributed. You can think of this as the item's *preferred* size.
+Use `basis` to specify the item's initial size before any extra space is distributed. You can think of this as the item's *preferred* size.
|---|---|---|---|
| **Value type** | **Behavior** | **Code snippet** Note: The boxes have a maximum intrinsic size of `100dp` | **Example using container width `600dp`** |
@@ -31,48 +31,31 @@ distributed. You can think of this as the item's *preferred* size.
| Fixed `dp` | A fixed size in Dp. | ```kotlin FlexBox { RedRoundedBox( Modifier.flex { basis(200.dp) } ) BlueRoundedBox( Modifier.flex { basis(100.dp) } ) } ``` |  |
| Percentage | A percentage of the container size. | ```kotlin FlexBox { RedRoundedBox( Modifier.flex { basis(0.7f) } ) BlueRoundedBox( Modifier.flex { basis(0.3f) } ) } ``` |  |
-If the basis value is less than the item's intrinsic minimum size, the intrinsic
-minimum size is used instead. For example, if a `Text` item that contains a word
-requires `50dp` to display, but also has `basis = 10.dp`, a
-value of `50dp` is used.
+If the basis value is less than the item's intrinsic minimum size, the intrinsic minimum size is used instead. For example, if a `Text` item that contains a word requires `50dp` to display, but also has `basis = 10.dp`, a value of `50dp` is used.
### Grow items when there's space
-Use `grow` to specify how much an item grows when there is extra space. This is
-space remaining in the `FlexBox` container after all the items' `basis` values
-have been added up. The `grow` value indicates *how much* of the extra space a
-given child will receive, relative to its siblings. By default, items won't
-grow.
+Use `grow` to specify how much an item grows when there is extra space. This is space remaining in the `FlexBox` container after all the items' `basis` values have been added up. The `grow` value indicates *how much* of the extra space a given child will receive, relative to its siblings. By default, items won't grow.
-The following example shows a `FlexBox` with three child items. Each has a basis
-value of `100dp`. The first child has a positive `grow` value. Since there is
-only one child with a `grow` value, the actual value is irrelevant - as long as
-it's positive, the child receives all the extra space.
+The following example shows a `FlexBox` with three child items. Each has a basis value of `100dp`. The first child has a positive `grow` value. Since there is only one child with a `grow` value, the actual value is irrelevant - as long as it's positive, the child receives all the extra space.
The images show the `FlexBox` behavior when its container size is `600dp`.
|---|---|
| ```kotlin FlexBox { RedRoundedBox( title = "400dp", modifier = Modifier.flex { grow(1f) } ) BlueRoundedBox(title = "100dp") GreenRoundedBox(title = "100dp") } ``` | Each child has a basis value of `100dp`. There is `300dp` of extra space.  Child 1 grows by `300dp` to fill the extra space.  |
-In the following example, the container size and `basis` size are the same. The
-difference is that each child has a different `grow` value.
+In the following example, the container size and `basis` size are the same. The difference is that each child has a different `grow` value.
|---|---|
| ```kotlin FlexBox { RedRoundedBox( title = "150dp", modifier = Modifier.flex { grow(1f) } ) BlueRoundedBox( title = "200dp", modifier = Modifier.flex { grow(2f) } ) GreenRoundedBox( title = "250dp", modifier = Modifier.flex { grow(3f) } ) } ``` | Each child has a basis value of `100dp`. There is `300dp` of extra space.  The total grow value is 6. Child 1 grows by (1 / 6) \* 300 = `50dp` Child 2 grows by (2 / 6) \* 300 = `100dp` Child 3 grows by (3 / 6) \* 300 = `150dp`  |
### Shrink items when there's insufficient space
-Use `shrink` to specify how much an item shrinks when the `FlexBox` container
-has insufficient space for all the items. `shrink` works the same way as `grow`
-except that, instead of distributing *extra space* to items, the *space deficit*
-is distributed to items. The `shrink` value specifies how much of the space
-deficit the item receives, or rather, how much the item will shrink by. By
-default, items have a `shrink` value of `1f`, meaning they shrink equally.
+Use `shrink` to specify how much an item shrinks when the `FlexBox` container has insufficient space for all the items. `shrink` works the same way as `grow` except that, instead of distributing *extra space* to items, the *space deficit* is distributed to items. The `shrink` value specifies how much of the space deficit the item receives, or rather, how much the item will shrink by. By default, items have a `shrink` value of `1f`, meaning they shrink equally.
-The following example shows two `Text` composables with the same text. The first
-child has a shrink value of `1f`, meaning it shrinks to absorb all the space
-deficit.
+The following example shows two `Text` composables with the same text. The first child has a shrink value of `1f`, meaning it shrinks to absorb all the space deficit.
+
```kotlin
FlexBox {
@@ -91,6 +74,7 @@ FlexBox {
.flex { shrink(0f) }
)
}
+
```
@@ -105,14 +89,11 @@ As the container size shrinks, Child 1 shrinks.
## Item alignment
-Use `alignSelf` to control how an item is aligned to the cross axis. This
-overrides the [`alignItems` property](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior#align-distribute) of the container for this item. It
-has all the same possible values, with the addition of `Auto` which inherits the
-behavior of the `FlexBox` container.
+Use `alignSelf` to control how an item is aligned to the cross axis. This overrides the [`alignItems` property](https://developer.android.com/develop/ui/compose/layouts/adaptive/flexbox/container-behavior#align-distribute) of the container for this item. It has all the same possible values, with the addition of `Auto` which inherits the behavior of the `FlexBox` container.
-For example, this `FlexBox` has `alignItems` set to `Start` and five children
-which override the cross axis alignment.
+For example, this `FlexBox` has `alignItems` set to `Start` and five children which override the cross axis alignment.
+
```kotlin
FlexBox(
@@ -126,6 +107,7 @@ FlexBox(
PinkRoundedBox(modifier = Modifier.flex { alignSelf(FlexAlignSelf.Stretch) })
OrangeRoundedBox(modifier = Modifier.flex { alignSelf(FlexAlignSelf.Baseline) })
}
+
```
@@ -134,19 +116,13 @@ FlexBox(
## Item order
-By default, `FlexBox` lays out items in the order that they are declared in
-code. Override this behavior using `order`.
+By default, `FlexBox` lays out items in the order that they are declared in code. Override this behavior using `order`.
-The default value for `order` is zero, and `FlexBox` sorts items based on this
-value in ascending order. Any items that have the same `order` value are
-laid out in the same order they are declared in. Use negative and positive
-`order` values to move items to the start or end of a layout without changing
-where they are declared.
+The default value for `order` is zero, and `FlexBox` sorts items based on this value in ascending order. Any items that have the same `order` value are laid out in the same order they are declared in. Use negative and positive `order` values to move items to the start or end of a layout without changing where they are declared.
-The following example shows two child items. The first has the default `order`
-of zero, and the second has an order of `-1`. After sorting, Child 1 appears
-after Child 2.
+The following example shows two child items. The first has the default `order` of zero, and the second has an order of `-1`. After sorting, Child 1 appears after Child 2.
+
```kotlin
FlexBox {
@@ -163,6 +139,7 @@ FlexBox {
}
)
}
+
```
diff --git a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/container-properties.md b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/container-properties.md
index 33b37a2..28c8d13 100644
--- a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/container-properties.md
+++ b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/container-properties.md
@@ -1,6 +1,4 @@
-You can define a Grid container configuration to create flexible layouts
-that respond to different screen sizes and content types.
-This page describes how to do the following:
+You can define a Grid container configuration to create flexible layouts that respond to different screen sizes and content types. This page describes how to do the following:
- [Define a grid](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid/container-properties#grid-definition): Set up the basic structure of rows and columns.
- [Place items in a grid](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid/container-properties#item-placement): Understand how items are placed into grid cells and how to change flow direction.
@@ -9,13 +7,9 @@ This page describes how to do the following:
## Define a grid
-A grid consists of columns and rows.
-The [`Grid`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/Grid.composable#Grid(kotlin.Function1,androidx.compose.ui.Modifier,kotlin.Function1)) composable has a `config` parameter
-that accepts a lambda to define the columns and rows
-within [`GridConfigurationScope`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridConfigurationScope).
-The following example defines a grid that has three rows and two columns,
-each with a fixed size specified in [`Dp`](https://developer.android.com/reference/kotlin/androidx/compose/ui/unit/Dp):
+A grid consists of columns and rows. The [`Grid`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/Grid.composable#Grid(kotlin.Function1,androidx.compose.ui.Modifier,kotlin.Function1)) composable has a `config` parameter that accepts a lambda to define the columns and rows within [`GridConfigurationScope`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridConfigurationScope). The following example defines a grid that has three rows and two columns, each with a fixed size specified in [`Dp`](https://developer.android.com/reference/kotlin/androidx/compose/ui/unit/Dp):
+
```kotlin
Grid(
@@ -29,26 +23,18 @@ Grid(
}
) {
}
+
```
## Place items in a grid
-`Grid` takes the UI elements
-in the `content` lambda and places them into grid cells.
-The grid lays out items regardless of
-whether you have explicitly defined the rows and columns.
-By default,
-`Grid` tries to place a UI element in the available grid cell in the row;
-if it can't, it places it in an available grid cell in the next row.
-If there are no empty cells, `Grid` creates a new row.
+`Grid` takes the UI elements in the `content` lambda and places them into grid cells. The grid lays out items regardless of whether you have explicitly defined the rows and columns. By default, `Grid` tries to place a UI element in the available grid cell in the row; if it can't, it places it in an available grid cell in the next row. If there are no empty cells, `Grid` creates a new row.
-In the following example, the grid has six grid cells
-and places a card into each one (Figure 1).
-Each grid cell is `160dp` x `90dp`,
-making the total grid size `320dp` x `270dp`.
+In the following example, the grid has six grid cells and places a card into each one (Figure 1). Each grid cell is `160dp` x `90dp`, making the total grid size `320dp` x `270dp`.
+
```kotlin
Grid(
@@ -68,15 +54,16 @@ Grid(
Card5()
Card6()
}
+
```
 **Figure 1**. Six cards are placed in a grid that has three rows and two columns.
-To change this default behavior to filling by column,
-set the [`flow`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridConfigurationScope#flow()) property to [`GridFlow.Column`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridFlow#Column()).
+To change this default behavior to filling by column, set the [`flow`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridConfigurationScope#flow()) property to [`GridFlow.Column`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridFlow#Column()).
+
```kotlin
Grid(
@@ -98,6 +85,7 @@ Grid(
Card5()
Card6()
}
+
```
@@ -106,17 +94,16 @@ Grid(
## Manage track sizing
-Rows and columns are collectively referred to as a [grid track](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid#grid-track).
-You can specify the size of a grid track using one of the following methods:
+Rows and columns are collectively referred to as a [grid track](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid#grid-track). You can specify the size of a grid track using one of the following methods:
- **Fixed** (`Dp`): Allocates a specific size (e.g., `column(180.dp)`).
- **Percentage** (`Float`): Allocates a percentage of the total available space from `0.0f` to `1.0f` (e.g., `row(0.5f)` for 50%).
- **Flexible** ([`Fr`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/Fr)): Distributes remaining space proportionally after fixed and percentage tracks are calculated. For example, if two rows are set to `1.fr` and `3.fr`, the latter receives 75% of the remaining height.
- **Intrinsic** : Sizes the track based on the content inside it. For more information, see [Determine grid track size intrinsically](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid/container-properties#intrinsic-grid-track-size).
-The following example uses the different track sizing options
-to define the row heights:
+The following example uses the different track sizing options to define the row heights:
+
```kotlin
Grid(
@@ -136,6 +123,7 @@ Grid(
PastelYellowCard("Auto")
}
+
```
@@ -144,14 +132,11 @@ Grid(
### Set the minimum size for flexible grid tracks
-When a grid container has no remaining space,
-a standard flexible track can shrink to `0.dp`.
-To prevent this and ensure content isn't crushed,
-use [`GridTrackSize.MinMax`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridTrackSize#MinMax(androidx.compose.ui.unit.Dp,androidx.compose.foundation.layout.Fr))
-to enforce an explicit minimum size while keeping the track flexible.
+When a grid container has no remaining space, a standard flexible track can shrink to `0.dp`. To prevent this and ensure content isn't crushed, use [`GridTrackSize.MinMax`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridTrackSize#MinMax(androidx.compose.ui.unit.Dp,androidx.compose.foundation.layout.Fr)) to enforce an explicit minimum size while keeping the track flexible.
The following example allocates at least `100.dp` to the first row:
+
```kotlin
Grid(
@@ -171,6 +156,7 @@ Grid(
PastelGreenCard("Flex(1.fr)")
PastelBlueCard("Fixed(200.dp)")
}
+
```
@@ -179,18 +165,11 @@ Grid(
### Set the minimum grid track size to place lazy lists
-Standard flexible tracks automatically query the intrinsic sizes of
-their children to establish a base size.
-However, Jetpack Compose prohibits querying the intrinsic sizes of
-[`SubcomposeLayout`](https://developer.android.com/reference/kotlin/androidx/compose/ui/layout/SubcomposeLayout.composable#SubcomposeLayout(androidx.compose.ui.Modifier,kotlin.Function2)), which backs components,
-such as [`LazyColumn`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/lazy/LazyColumn.composable) and [`LazyRow`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/lazy/LazyRow.composable).
+Standard flexible tracks automatically query the intrinsic sizes of their children to establish a base size. However, Jetpack Compose prohibits querying the intrinsic sizes of [`SubcomposeLayout`](https://developer.android.com/reference/kotlin/androidx/compose/ui/layout/SubcomposeLayout.composable#SubcomposeLayout(androidx.compose.ui.Modifier,kotlin.Function2)), which backs components, such as [`LazyColumn`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/lazy/LazyColumn.composable) and [`LazyRow`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/lazy/LazyRow.composable).
-Placing a lazy list inside a standard flexible track causes
-an [`IllegalStateException`](https://developer.android.com/reference/java/lang/IllegalStateException) crash.
-To safely place lazy lists inside a flexible grid track,
-use `MinMax` with an explicit minimum size (such as `0.dp`)
-to bypass the intrinsic measurement pass.
+Placing a lazy list inside a standard flexible track causes an [`IllegalStateException`](https://developer.android.com/reference/java/lang/IllegalStateException) crash. To safely place lazy lists inside a flexible grid track, use `MinMax` with an explicit minimum size (such as `0.dp`) to bypass the intrinsic measurement pass.
+
```kotlin
Grid(
@@ -205,7 +184,7 @@ Grid(
},
modifier = Modifier.size(width = 170.dp, height = 240.dp)
) {
- Text("Lazy column in a Grid")
+ Text("LazyColumn in a Grid")
// The LazyColumn is placed in the second row, filling the remaining space.
LazyColumn(verticalArrangement = Arrangement.spacedBy(4.dp)) {
items(100) { number ->
@@ -213,6 +192,7 @@ Grid(
}
}
}
+
```
@@ -221,20 +201,15 @@ Grid(
### Determine grid track size intrinsically
-You can use [intrinsic sizing](https://developer.android.com/develop/ui/compose/layouts/intrinsic-measurements) for a `Grid`
-when you want the layout to adapt to the content,
-rather than forcing it into a fixed container.
-The grid track size is determined with the following values:
+You can use [intrinsic sizing](https://developer.android.com/develop/ui/compose/layouts/intrinsic-measurements) for a `Grid` when you want the layout to adapt to the content, rather than forcing it into a fixed container. The grid track size is determined with the following values:
- [`GridTrackSize.MaxContent`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridTrackSize#MaxContent()): Use the content's maximum intrinsic size (e.g., the width is determined by the full length of the text in a text block with no wrapping).
- [`GridTrackSize.MinContent`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridTrackSize#MinContent()): Use the content's minimum intrinsic size (e.g., the width is determined by the longest single word in a text block).
- [`GridTrackSize.Auto`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridTrackSize#Auto()): Use a flexible size for a track that adapts based on available space. It behaves like `MaxContent` by default, but shrinks and wraps its content to fit within the parent container.
-The following example places two texts side by side.
-The column size for the first text is determined
-by the required minimum width to display the text,
-and the second column width depends on the required maximum width of the text.
+The following example places two texts side by side. The column size for the first text is determined by the required minimum width to display the text, and the second column width depends on the required maximum width of the text.
+
```kotlin
Grid(
@@ -248,6 +223,7 @@ Grid(
Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras imperdiet.")
Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras imperdiet.")
}
+
```
@@ -256,13 +232,9 @@ Grid(
## Set gaps between rows and columns
-Once your grid tracks are sized,
-you can modify the [grid gap](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid#grid-gap) to refine the spacing between the tracks.
-You can specify the column gap with the [`columnGap`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridConfigurationScope#columnGap(androidx.compose.ui.unit.Dp)) function,
-and the row gap with [`rowGap`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridConfigurationScope#rowGap(androidx.compose.ui.unit.Dp)). In the following example,
-there is a `16dp` gap between each row,
-and an `8dp` gap between each column (Figure 5).
+Once your grid tracks are sized, you can modify the [grid gap](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid#grid-gap) to refine the spacing between the tracks. You can specify the column gap with the [`columnGap`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridConfigurationScope#columnGap(androidx.compose.ui.unit.Dp)) function, and the row gap with [`rowGap`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridConfigurationScope#rowGap(androidx.compose.ui.unit.Dp)). In the following example, there is a `16dp` gap between each row, and an `8dp` gap between each column (Figure 5).
+
```kotlin
Grid(
@@ -284,17 +256,16 @@ Grid(
Card5()
Card6()
}
+
```
 **Figure 6**. Gaps between rows and columns.
-You can also use the convenience function [`gap`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridConfigurationScope#gap(androidx.compose.ui.unit.Dp))
-to define gaps of the same column and row size,
-and to define column and gap sizes separately using a single function.
-The following code adds `8dp` gaps to the grid:
+You can also use the convenience function [`gap`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridConfigurationScope#gap(androidx.compose.ui.unit.Dp)) to define gaps of the same column and row size, and to define column and gap sizes separately using a single function. The following code adds `8dp` gaps to the grid:
+
```kotlin
Grid(
@@ -315,6 +286,7 @@ Grid(
Card5()
Card6()
}
+
```
\ No newline at end of file
diff --git a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/get-started.md b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/get-started.md
index bb78a97..0a525c7 100644
--- a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/get-started.md
+++ b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/get-started.md
@@ -2,11 +2,10 @@ This page describes how to implement basic [`Grid`](https://developer.android.co
## Set up project
-1. Add the [`androidx.compose.foundation.layout`](https://developer.android.com/jetpack/androidx/versions) library to your project's
- `lib.versions.toml`.
+1. Add the [`androidx.compose.foundation.layout`](https://developer.android.com/jetpack/androidx/versions) library to your project's `lib.versions.toml`.
[versions]
- compose = "1.12.0-beta02"
+ compose = "1.12.0-rc01"
[libraries]
androidx-compose-foundation-layout = { group = "androidx.compose.foundation", name = "foundation-layout", version.ref = "compose" }
@@ -19,9 +18,9 @@ This page describes how to implement basic [`Grid`](https://developer.android.co
## Create a basic grid
-The following example creates a basic 2x3 grid,
-with the columns and rows having a fixed size of `100.dp`.
+The following example creates a basic 2x3 grid, with the columns and rows having a fixed size of `100.dp`.
+
```kotlin
Grid(
@@ -41,11 +40,11 @@ Grid(
Card5(containerColor = PastelOrange)
Card6(containerColor = PastelYellow)
}
+
```
 **Figure 1**. A basic grid consists of rows and columns with fixed size.
-To learn how to implement more advanced grids,
-see [Set container properties](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid/container-properties) and [Set item properties](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid/item-properties).
\ No newline at end of file
+To learn how to implement more advanced grids, see [Set container properties](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid/container-properties) and [Set item properties](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid/item-properties).
\ No newline at end of file
diff --git a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/index.md b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/index.md
index 316b046..e48d9c9 100644
--- a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/index.md
+++ b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/index.md
@@ -1,27 +1,16 @@
> [!NOTE]
> **Note:** `Grid` is an experimental API and is subject to change. File any issues on the [issue tracker](https://issuetracker.google.com/issues/new?component=1876021&template=1424126).
-[`Grid`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/Grid.composable#Grid(kotlin.Function1,androidx.compose.ui.Modifier,kotlin.Function1)) is a Jetpack Compose API
-that lets you flexibly implement a two-dimensional layout.
-With this API, you can display items in multi-column
-or multi-row layouts that adapt to the available container size.
+[`Grid`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/Grid.composable#Grid(kotlin.Function1,androidx.compose.ui.Modifier,kotlin.Function1)) is a Jetpack Compose API that lets you flexibly implement a two-dimensional layout. With this API, you can display items in multi-column or multi-row layouts that adapt to the available container size.
 **Figure 1.** A flexible and adaptive two-dimensional layout with `Grid`.
## How is Grid different from similar composables?
-Compose already offers similar components, such as [`LazyVerticalGrid`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/lazy/grid/LazyVerticalGrid.composable#LazyVerticalGrid(androidx.compose.foundation.lazy.grid.GridCells,androidx.compose.ui.Modifier,androidx.compose.foundation.lazy.grid.LazyGridState,androidx.compose.foundation.layout.PaddingValues,kotlin.Boolean,androidx.compose.foundation.layout.Arrangement.Vertical,androidx.compose.foundation.layout.Arrangement.Horizontal,androidx.compose.foundation.gestures.FlingBehavior,kotlin.Boolean,androidx.compose.foundation.OverscrollEffect,kotlin.Function1)).
-These components are mainly for visualization of large, homogeneous data sets---
-for example, displaying a content catalog in a video streaming app.
-These components are NOT designed
-for the structural layout of a screen or complex component.
+Compose already offers similar components, such as [`LazyVerticalGrid`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/lazy/grid/LazyVerticalGrid.composable#LazyVerticalGrid(androidx.compose.foundation.lazy.grid.GridCells,androidx.compose.ui.Modifier,androidx.compose.foundation.lazy.grid.LazyGridState,androidx.compose.foundation.layout.PaddingValues,kotlin.Boolean,androidx.compose.foundation.layout.Arrangement.Vertical,androidx.compose.foundation.layout.Arrangement.Horizontal,androidx.compose.foundation.gestures.FlingBehavior,kotlin.Boolean,androidx.compose.foundation.OverscrollEffect,kotlin.Function1)). These components are mainly for visualization of large, homogeneous data sets--- for example, displaying a content catalog in a video streaming app. These components are NOT designed for the structural layout of a screen or complex component.
-You can also implement a two-dimensional layout
-by combining multiple `Row` and `Column` composables.
-However, this approach has some downsides,
-such as deep hierarchies and difficulties in adaptability.
+You can also implement a two-dimensional layout by combining multiple `Row` and `Column` composables. However, this approach has some downsides, such as deep hierarchies and difficulties in adaptability.
-The following table provides an overview
-of which layouts are suitable for each API:
+The following table provides an overview of which layouts are suitable for each API:
| Component | Purpose |
|---|---|
@@ -34,24 +23,16 @@ of which layouts are suitable for each API:
## Terminology
-Familiarize yourself with the following terminology
-to understand how `Grid` works.
+Familiarize yourself with the following terminology to understand how `Grid` works.
### Grid line
-A grid is made up of lines, which run horizontally and vertically.
-If your grid has three rows, it has four horizontal lines,
-including the one after the last row.
-In the following image, each dotted line represents a grid line:
+A grid is made up of lines, which run horizontally and vertically. If your grid has three rows, it has four horizontal lines, including the one after the last row. In the following image, each dotted line represents a grid line:
 **Figure 2**. The grid consists of four horizontal lines and three vertical lines.
### Grid track
-A grid track is the space between two grid lines.
-A row track is between two horizontal lines,
-and a column track is between two vertical lines.
-To define the size of these tracks,
-assign a size to them when you create the grid.
+A grid track is the space between two grid lines. A row track is between two horizontal lines, and a column track is between two vertical lines. To define the size of these tracks, assign a size to them when you create the grid.
 **Figure 3**. A grid track for the first row.
### Grid cell
@@ -61,13 +42,10 @@ A grid cell is the intersection of a row and column track.
### Grid area
-A grid area consists of several grid cells.
-You can define a grid area by making an item span multiple tracks.
+A grid area consists of several grid cells. You can define a grid area by making an item span multiple tracks.
 **Figure 5**. A grid area that consists of four grid cells.
### Grid gap
-A grid gap is the gutter between grid tracks.
-You can't place a UI element into a gap,
-but you can span a UI element across it.
+A grid gap is the gutter between grid tracks. You can't place a UI element into a gap, but you can span a UI element across it.
 **Figure 6**. A grid gap between the first column and the second column.
\ No newline at end of file
diff --git a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/item-properties.md b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/item-properties.md
index 9f0500e..5c8787c 100644
--- a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/item-properties.md
+++ b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/grid/item-properties.md
@@ -1,33 +1,18 @@
-While the `Grid` config defines the overall structure,
-you use the [`gridItem`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridScope#(androidx.compose.ui.Modifier).gridItem(kotlin.Int,kotlin.Int,kotlin.Int,kotlin.Int,androidx.compose.ui.Alignment)) modifier to control the position, spanning,
-and alignment of items within that structure.
+While the `Grid` config defines the overall structure, you use the [`gridItem`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridScope#(androidx.compose.ui.Modifier).gridItem(kotlin.Int,kotlin.Int,kotlin.Int,kotlin.Int,androidx.compose.ui.Alignment)) modifier to control the position, spanning, and alignment of items within that structure.
## Set the item position
-Place an item into a specific track or cell
-with the `row` and `column` parameters.
+Place an item into a specific track or cell with the `row` and `column` parameters.
-The `row` and `column` parameters specify the row and column track indexes
-that the item is placed in.
-Track indexes are 1-based---they start at one.
-Specifying only `row` or `column` (not both) places the item
-in the next available space in that track.
-Specifying both places the item into that cell.
+The `row` and `column` parameters specify the row and column track indexes that the item is placed in. Track indexes are 1-based---they start at one. Specifying only `row` or `column` (not both) places the item in the next available space in that track. Specifying both places the item into that cell.
-Use a positive integer to specify the track index from the start.
-For example, to place an item in the first row and column,
-use `gridItem(row = 1, column = 1)`.
+Use a positive integer to specify the track index from the start. For example, to place an item in the first row and column, use `gridItem(row = 1, column = 1)`.
-Use a negative integer to specify the track relative to the end.
-For example, to place an item in the second-to-last row and column, use
-`gridItem(row = -2, column = -2)`.
+Use a negative integer to specify the track relative to the end. For example, to place an item in the second-to-last row and column, use `gridItem(row = -2, column = -2)`.
-In the following example, Card **#2** is placed
-in the second row and the second column.
-Card **#3** is assigned to the last row (indexed by -1),
-where it automatically occupies
-the first available column in that track (Figure 1).
+In the following example, Card **#2** is placed in the second row and the second column. Card **#3** is assigned to the last row (indexed by -1), where it automatically occupies the first available column in that track (Figure 1).
+
```kotlin
Grid(
@@ -45,6 +30,7 @@ Grid(
Card2(modifier = Modifier.gridItem(row = 2, column = 2))
Card3(modifier = Modifier.gridItem(row = -1, column = -2))
}
+
```
@@ -55,16 +41,9 @@ and Card #3 is placed in the first column in the third row.](https://developer.a
## Span rows and columns
-Use the `rowSpan` and `columnSpan` parameters
-to span an item over multiple cells.
-You can place a UI element into a [grid area](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid#grid-area),
-which is the area consisting of several [grid cells](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid#grid-cell).
-The `gridItem` modifier lets you specify the grid area
-with the `rowSpan` and `columnSpan` parameters.
-In the following example,
-Card **#1** is placed in the area consisting of two rows and two columns
-(Figure 2).
+Use the `rowSpan` and `columnSpan` parameters to span an item over multiple cells. You can place a UI element into a [grid area](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid#grid-area), which is the area consisting of several [grid cells](https://developer.android.com/develop/ui/compose/layouts/adaptive/grid#grid-cell). The `gridItem` modifier lets you specify the grid area with the `rowSpan` and `columnSpan` parameters. In the following example, Card **#1** is placed in the area consisting of two rows and two columns (Figure 2).
+
```kotlin
Grid(
@@ -84,6 +63,7 @@ Grid(
Card3()
Card4(modifier = Modifier.gridItem(columnSpan = 3))
}
+
```
@@ -92,11 +72,9 @@ Grid(
## Set the alignment in a grid area
-You can set the alignment of the UI element in a grid area
-by specifying it in the `alignment` parameter of the [`gridItem`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridScope#(androidx.compose.ui.Modifier).gridItem(kotlin.Int,kotlin.Int,kotlin.Int,kotlin.Int,androidx.compose.ui.Alignment)) modifier.
-In the following example, **#1** is placed in the center of the grid area
-consisting of two columns and two rows.
+You can set the alignment of the UI element in a grid area by specifying it in the `alignment` parameter of the [`gridItem`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/layout/GridScope#(androidx.compose.ui.Modifier).gridItem(kotlin.Int,kotlin.Int,kotlin.Int,kotlin.Int,androidx.compose.ui.Alignment)) modifier. In the following example, **#1** is placed in the center of the grid area consisting of two columns and two rows.
+
```kotlin
Grid(
@@ -124,6 +102,7 @@ Grid(
Card3()
Card4(modifier = Modifier.gridItem(columnSpan = 3))
}
+
```
@@ -133,13 +112,9 @@ consisting of two rows and two columns.](https://developer.android.com/static/de
## Auto-placement mixed with placed items
-A UI element in `Grid`
-that has no position specification undergoes auto-placement.
-This example shows how you can mix auto-placed elements
-and the UI elements with specified grid cells.
-Card **#2** and Card **#4** are placed in specified grid cells,
-and the other items are auto-placed.
+A UI element in `Grid` that has no position specification undergoes auto-placement. This example shows how you can mix auto-placed elements and the UI elements with specified grid cells. Card **#2** and Card **#4** are placed in specified grid cells, and the other items are auto-placed.
+
```kotlin
Grid(
@@ -161,6 +136,7 @@ Grid(
Card5()
Card6()
}
+
```
diff --git a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/mediaquery/index.md b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/mediaquery/index.md
index 4cd2564..f9fb3ed 100644
--- a/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/mediaquery/index.md
+++ b/jetpack-compose/adaptive/references/android/develop/ui/compose/layouts/adaptive/mediaquery/index.md
@@ -1,10 +1,7 @@
> [!NOTE]
> **Note:** The `mediaQuery` function and the related data types are experimental and subject to change. File any issues on the [issue tracker](https://issuetracker.google.com/issues?q=componentid:1876021).
-You need various types of information, such as device capability
-and app status, to update your app layout.
-Window width and height are the most commonly used information.
-In addition to that, you can refer to the following information:
+You need various types of information, such as device capability and app status, to update your app layout. Window width and height are the most commonly used information. In addition to that, you can refer to the following information:
- Window posture
- Pointing devices precision
@@ -12,13 +9,9 @@ In addition to that, you can refer to the following information:
- Whether the camera and microphone are supported by the device
- The distance between a user and the device display
-Because the information is updated dynamically,
-you need to monitor it and trigger recomposition when any update happens.
-The [`mediaQuery`](https://developer.android.com/reference/kotlin/androidx/compose/ui/mediaQuery.composable#mediaQuery(kotlin.Function1)) function abstracts the details of the information retrieval
-and lets you focus on defining the condition to trigger the layout updates.
-The following example switches the layout to `TabletopLayout`
-when the foldable posture is tabletop:
+Because the information is updated dynamically, you need to monitor it and trigger recomposition when any update happens. The [`mediaQuery`](https://developer.android.com/reference/kotlin/androidx/compose/ui/mediaQuery.composable#mediaQuery(kotlin.Function1)) function abstracts the details of the information retrieval and lets you focus on defining the condition to trigger the layout updates. The following example switches the layout to `TabletopLayout` when the foldable posture is tabletop:
+
```kotlin
@Composable
@@ -33,16 +26,16 @@ fun VideoPlayer(
}
// ...
}
+
```
## Enable the `mediaQuery` function
-To enable the `mediaQuery` function,
-set the `isMediaQueryIntegrationEnabled` attribute of
-the [`ComposeUiFlags`](https://developer.android.com/reference/kotlin/androidx/compose/ui/ComposeUiFlags) object to `true`:
+To enable the `mediaQuery` function, set the `isMediaQueryIntegrationEnabled` attribute of the [`ComposeUiFlags`](https://developer.android.com/reference/kotlin/androidx/compose/ui/ComposeUiFlags) object to `true`:
+
```kotlin
class MyApplication : Application() {
@@ -51,20 +44,14 @@ class MyApplication : Application() {
super.onCreate()
}
}
+
```
## Define a condition with parameters
-You can define a condition as a lambda
-that is evaluated within [`UiMediaScope`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope).
-The `mediaQuery` function evaluates the condition according to
-the current status and the device capabilities.
-The function returns a boolean value,
-so you can determine the layout with conditional branches
-like an `if` expression.
-Table 1 describes the parameters available in `UiMediaScope`.
+You can define a condition as a lambda that is evaluated within [`UiMediaScope`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope). The `mediaQuery` function evaluates the condition according to the current status and the device capabilities. The function returns a boolean value, so you can determine the layout with conditional branches like an `if` expression. Table 1 describes the parameters available in `UiMediaScope`.
| Parameter | Value type | Description |
|---|---|---|
@@ -77,17 +64,9 @@ Table 1 describes the parameters available in `UiMediaScope`.
| `hasMicrophone` | `Boolean` | Whether the microphone is supported on the device. |
| `viewingDistance` | [`UiMediaScope.ViewingDistance`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.ViewingDistance) | The typical distance between the user and the device screen. |
-A `UiMediaScope` object resolves the values of the parameters.
-The `mediaQuery` function uses [`LocalUiMediaScope.current`](https://developer.android.com/reference/kotlin/androidx/compose/ui/package-summary#LocalUiMediaScope())
-to access the `UiMediaScope` object,
-which represents the current device capabilities and context.
-This object is dynamically updated when any changes are made,
-such as when the user changes the device posture.
-The `mediaQuery` function then evaluates the `query` lambda
-with the updated `UiMediaScope` object and returns a boolean value.
-For example, the following snippet chooses between `TabletopLayout`
-and `FlatLayout` based on the `windowPosture` parameter value.
+A `UiMediaScope` object resolves the values of the parameters. The `mediaQuery` function uses [`LocalUiMediaScope.current`](https://developer.android.com/reference/kotlin/androidx/compose/ui/package-summary#LocalUiMediaScope()) to access the `UiMediaScope` object, which represents the current device capabilities and context. This object is dynamically updated when any changes are made, such as when the user changes the device posture. The `mediaQuery` function then evaluates the `query` lambda with the updated `UiMediaScope` object and returns a boolean value. For example, the following snippet chooses between `TabletopLayout` and `FlatLayout` based on the `windowPosture` parameter value.
+
```kotlin
@Composable
@@ -102,26 +81,18 @@ fun VideoPlayer(
}
// ...
}
+
```
### Make a decision based on the window size
-[Window size classes](https://developer.android.com/develop/ui/compose/layouts/adaptive/use-window-size-classes) are a set of opinionated viewport breakpoints
-that help you design, develop, and test adaptive layouts.
-You can compare the two parameters representing the current window size
-with the threshold defined in the window size classes.
-The following example changes the number of panes according to the window width.
-[`WindowSizeClass`](https://developer.android.com/reference/androidx/window/core/layout/WindowSizeClass) class has constants for the thresholds
-of window size classes (Figure 1).
+[Window size classes](https://developer.android.com/develop/ui/compose/layouts/adaptive/use-window-size-classes) are a set of opinionated viewport breakpoints that help you design, develop, and test adaptive layouts. You can compare the two parameters representing the current window size with the threshold defined in the window size classes. The following example changes the number of panes according to the window width. [`WindowSizeClass`](https://developer.android.com/reference/androidx/window/core/layout/WindowSizeClass) class has constants for the thresholds of window size classes (Figure 1).
-The [`derivedMediaQuery`](https://developer.android.com/reference/kotlin/androidx/compose/ui/derivedMediaQuery.composable#derivedMediaQuery(kotlin.Function1)) function evaluates the `query` lambda
-and wraps the result in a [`derivedStateOf`](https://developer.android.com/develop/ui/compose/side-effects#derivedstateof).
-Because `windowWidth` and `windowHeight` can update frequently,
-call the `derivedMediaQuery` function instead of the `mediaQuery` function
-when you refer to those parameters in the `query` lambda.
+The [`derivedMediaQuery`](https://developer.android.com/reference/kotlin/androidx/compose/ui/derivedMediaQuery.composable#derivedMediaQuery(kotlin.Function1)) function evaluates the `query` lambda and wraps the result in a [`derivedStateOf`](https://developer.android.com/develop/ui/compose/side-effects#derivedstateof). Because `windowWidth` and `windowHeight` can update frequently, call the `derivedMediaQuery` function instead of the `mediaQuery` function when you refer to those parameters in the `query` lambda.
+
```kotlin
val narrowerThanMedium by derivedMediaQuery {
@@ -135,6 +106,7 @@ when {
narrowerThanExpanded -> TwoPaneLayout()
else -> ThreePaneLayout()
}
+
```
@@ -143,12 +115,9 @@ when {
### Update layout according to the window posture
-The `windowPosture` parameter describes the current window posture
-as a `UiMediaScope.Posture` object.
-You can check the current [posture](https://developer.android.com/develop/ui/compose/layouts/adaptive/foldables/learn-about-foldables) by comparing the parameter
-with the values defined in the `UiMediaScope.Posture` class.
-The following example switches layout according to the window posture:
+The `windowPosture` parameter describes the current window posture as a `UiMediaScope.Posture` object. You can check the current [posture](https://developer.android.com/develop/ui/compose/layouts/adaptive/foldables/learn-about-foldables) by comparing the parameter with the values defined in the `UiMediaScope.Posture` class. The following example switches layout according to the window posture:
+
```kotlin
when {
@@ -156,32 +125,22 @@ when {
mediaQuery { windowPosture == UiMediaScope.Posture.Book } -> BookLayout()
mediaQuery { windowPosture == UiMediaScope.Posture.Flat } -> FlatLayout()
}
+
```
### Check the precision of the available pointing device
-A high precision pointing device helps users to point a UI element precisely.
-The precision of a pointing device depends on the device type.
+A high precision pointing device helps users to point a UI element precisely. The precision of a pointing device depends on the device type.
-The `pointerPrecision` parameter describes the precision
-of the available pointing devices, such as a mouse and touchscreen.
-There are four values defined in the `UiMediaScope.PointerPrecision` class:
-[`Fine`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.PointerPrecision#Fine()), [`Coarse`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.PointerPrecision#Coarse()), [`Blunt`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.PointerPrecision#Blunt()), and [`None`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.PointerPrecision#None()).
-`None` means that no pointing device is available.
-The precision ranges from highest to lowest in this order:
-`Fine`, `Coarse`, and `Blunt`.
+The `pointerPrecision` parameter describes the precision of the available pointing devices, such as a mouse and touchscreen. There are four values defined in the `UiMediaScope.PointerPrecision` class: [`Fine`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.PointerPrecision#Fine()), [`Coarse`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.PointerPrecision#Coarse()), [`Blunt`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.PointerPrecision#Blunt()), and [`None`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.PointerPrecision#None()). `None` means that no pointing device is available. The precision ranges from highest to lowest in this order: `Fine`, `Coarse`, and `Blunt`.
-If multiple pointing devices are available and their precisions are different,
-the parameter is resolved with the highest one.
-For example, if there are two pointing devices --- a `Fine` precision device and
-a `Blunt` precision device ---
-`Fine` is the value of the `pointerPrecision` parameter.
+If multiple pointing devices are available and their precisions are different, the parameter is resolved with the highest one. For example, if there are two pointing devices --- a `Fine` precision device and a `Blunt` precision device --- `Fine` is the value of the `pointerPrecision` parameter.
-The following example shows a larger button
-when the user is using a pointing device with low precision:
+The following example shows a larger button when the user is using a pointing device with low precision:
+
```kotlin
if (mediaQuery { pointerPrecision == UiMediaScope.PointerPrecision.Blunt }) {
@@ -189,38 +148,31 @@ if (mediaQuery { pointerPrecision == UiMediaScope.PointerPrecision.Blunt }) {
} else {
NormalSizeButton()
}
+
```
### Check the available keyboard type
-The `keyboardKind` parameter represents the type of the available keyboards:
-[`Physical`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.KeyboardKind#Physical()), [`Virtual`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.KeyboardKind#Virtual()), and [`None`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.KeyboardKind#None()).
-If an on-screen keyboard is displayed and
-a hardware keyboard is available at the same time,
-the parameter is resolved as `Physical`.
-If neither is detected, `None` is the value of the parameter.
-The following example shows a message suggesting that users connect a keyboard
-when no keyboard is detected:
+The `keyboardKind` parameter represents the type of the available keyboards: [`Physical`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.KeyboardKind#Physical()), [`Virtual`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.KeyboardKind#Virtual()), and [`None`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.KeyboardKind#None()). If an on-screen keyboard is displayed and a hardware keyboard is available at the same time, the parameter is resolved as `Physical`. If neither is detected, `None` is the value of the parameter. The following example shows a message suggesting that users connect a keyboard when no keyboard is detected:
+
```kotlin
if (mediaQuery { keyboardKind == UiMediaScope.KeyboardKind.None }) {
SuggestKeyboardConnect()
}
+
```
### Check if the device supports camera and microphone
-Some devices don't support cameras or microphones.
-You can check if the device supports a camera and a microphone
-with the `hasCamera` parameter and the `hasMicrophone` parameter.
-The following example shows buttons to use with camera and microphone
-when the device supports them:
+Some devices don't support cameras or microphones. You can check if the device supports a camera and a microphone with the `hasCamera` parameter and the `hasMicrophone` parameter. The following example shows buttons to use with camera and microphone when the device supports them:
+
```kotlin
Row {
@@ -234,25 +186,18 @@ Row {
CameraButton()
}
}
+
```
### Adjust UI with the estimated viewing distance
-Viewing distance is a factor that helps determine layout.
-If the user is using the app from a distance,
-they would expect the text and UI elements to be bigger.
-The `viewingDistance` parameter provides an estimate of the viewing distance
-based on the device type and its typical usage context.
+Viewing distance is a factor that helps determine layout. If the user is using the app from a distance, they would expect the text and UI elements to be bigger. The `viewingDistance` parameter provides an estimate of the viewing distance based on the device type and its typical usage context.
-There are three values defined in the `UiMediaScope.ViewingDistance` class:
-[`Near`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.ViewingDistance#Near()), [`Medium`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.ViewingDistance#Medium()), and [`Far`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.ViewingDistance#Far()).
-`Near` means that the screen is in close range,
-and `Far` means that the device is viewed from a distance.
-The following example increases the font size when the viewing distance is
-`Far` or `Medium`:
+There are three values defined in the `UiMediaScope.ViewingDistance` class: [`Near`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.ViewingDistance#Near()), [`Medium`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.ViewingDistance#Medium()), and [`Far`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.ViewingDistance#Far()). `Near` means that the screen is in close range, and `Far` means that the device is viewed from a distance. The following example increases the font size when the viewing distance is `Far` or `Medium`:
+
```kotlin
val fontSize = when {
@@ -260,19 +205,16 @@ val fontSize = when {
mediaQuery { viewingDistance == UiMediaScope.ViewingDistance.Medium } -> 18.sp
else -> 16.sp
}
+
```
## Preview a UI component
-You can call the `mediaQuery` and `derivedMediaQuery` functions in the
-composable functions to preview UI components.
-The following snippet chooses between `TabletopLayout`
-and `FlatLayout` based on the `windowPosture` parameter value.
-To preview the `TabletopLayout`, the `windowPosture` parameter should be
-[`UiMediaScope.Posture.Tabletop`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.Posture#Tabletop()).
+You can call the `mediaQuery` and `derivedMediaQuery` functions in the composable functions to preview UI components. The following snippet chooses between `TabletopLayout` and `FlatLayout` based on the `windowPosture` parameter value. To preview the `TabletopLayout`, the `windowPosture` parameter should be [`UiMediaScope.Posture.Tabletop`](https://developer.android.com/reference/kotlin/androidx/compose/ui/UiMediaScope.Posture#Tabletop()).
+
```kotlin
when {
@@ -280,14 +222,12 @@ when {
mediaQuery { windowPosture == UiMediaScope.Posture.Book } -> BookLayout()
mediaQuery { windowPosture == UiMediaScope.Posture.Flat } -> FlatLayout()
}
+
```
-The `mediaQuery` and `derivedMediaQuery` functions evaluate
-the given `query` lambda within a `UiMediaScope` object,
-which is provided as `LocalUiMediaScope.current`.
-You can override it with the following steps:
+The `mediaQuery` and `derivedMediaQuery` functions evaluate the given `query` lambda within a `UiMediaScope` object, which is provided as `LocalUiMediaScope.current`. You can override it with the following steps:
1. Enable the `mediaQuery` function.
2. Define a custom object that implements the `UiMediaScope` interface.
@@ -296,6 +236,7 @@ You can override it with the following steps:
You can preview the `TabletopLayout` with the following example:
+
```kotlin
@Preview
@@ -324,6 +265,7 @@ fun PreviewLayoutForTabletop() {
}
}
}
+
```
\ No newline at end of file
diff --git a/jetpack-compose/adaptive/references/android/develop/ui/compose/tooling/debug.md b/jetpack-compose/adaptive/references/android/develop/ui/compose/tooling/debug.md
index 023836f..027181b 100644
--- a/jetpack-compose/adaptive/references/android/develop/ui/compose/tooling/debug.md
+++ b/jetpack-compose/adaptive/references/android/develop/ui/compose/tooling/debug.md
@@ -2,60 +2,29 @@ Tools for debugging your Compose UI are available in Android Studio.
## Layout Inspector
-Layout Inspector lets you inspect a Compose layout inside a running app in an
-emulator or physical device. You can use the Layout Inspector to check how often
-a composable is recomposed or skipped, which can help identify issues with your
-app. For example, some coding errors might force your UI to recompose
-excessively, which can cause [poor performance](https://developer.android.com/develop/ui/compose/performance).
-Some coding errors can prevent your UI from recomposing and, therefore,
-prevent your UI changes from showing up on the screen. If you're new to
-Layout inspector, check the [guidance](https://developer.android.com/studio/debug/layout-inspector) on how to
-run it.
+Layout Inspector lets you inspect a Compose layout inside a running app in an emulator or physical device. You can use the Layout Inspector to check how often a composable is recomposed or skipped, which can help identify issues with your app. For example, some coding errors might force your UI to recompose excessively, which can cause [poor performance](https://developer.android.com/develop/ui/compose/performance). Some coding errors can prevent your UI from recomposing and, therefore, prevent your UI changes from showing up on the screen. If you're new to Layout inspector, check the [guidance](https://developer.android.com/studio/debug/layout-inspector) on how to run it.
> [!NOTE]
> **Note:** If you're not seeing Compose components in layout inspector, make sure you are not removing `META-INF/androidx.compose.*.version` files from the APK. These are required for layout inspector to work.
### Get recomposition counts
-When debugging your Compose layouts, knowing when composables
-[recompose](https://developer.android.com/develop/ui/compose/mental-model#recomposition) is important in
-understanding whether your UI is implemented properly. For example, if it's
-recomposing too many times, your app might be doing more work than is necessary.
-On the other hand, components that don't recompose when you anticipate them to
-can lead to unexpected behaviors.
+When debugging your Compose layouts, knowing when composables [recompose](https://developer.android.com/develop/ui/compose/mental-model#recomposition) is important in understanding whether your UI is implemented properly. For example, if it's recomposing too many times, your app might be doing more work than is necessary. On the other hand, components that don't recompose when you anticipate them to can lead to unexpected behaviors.
-The Layout Inspector shows you when discrete composables in your layout
-hierarchy have either recomposed or skipped, as you interact with your app. In
-Android Studio, your recompositions are highlighted to help you determine
-where in the UI your composables are recomposing.
+The Layout Inspector shows you when discrete composables in your layout hierarchy have either recomposed or skipped, as you interact with your app. In Android Studio, your recompositions are highlighted to help you determine where in the UI your composables are recomposing.
**Figure 1.** Recompositions are highlighted in Layout Inspector.
-The highlighted portion shows a gradient overlay of the composable in the image
-section of the Layout Inspector, and gradually disappears so that you can get an
-idea of where in the UI the composable with the highest recompositions can be
-found. If one composable is recomposing at a higher rate than another
-composable, then the first composable receives a stronger gradient overlay
-color. If you double-click a composable in the layout inspector, you're taken to
-the corresponding code for analysis.
+The highlighted portion shows a gradient overlay of the composable in the image section of the Layout Inspector, and gradually disappears so that you can get an idea of where in the UI the composable with the highest recompositions can be found. If one composable is recomposing at a higher rate than another composable, then the first composable receives a stronger gradient overlay color. If you double-click a composable in the layout inspector, you're taken to the corresponding code for analysis.
> [!NOTE]
> **Note:** To view recomposition counts, make sure your app is using an API level of 29 or higher, and `Compose 1.2.0` or higher. Then, deploy your app as you normally would.
 **Figure 2.**The composition and skip counter in Layout Inspector.
-Open the **Layout Inspector** window and connect to your app process. In the
-**Component Tree** , there are two columns that appear next to the layout
-hierarchy. The first column shows the number of compositions for each node and
-the second column displays the number of skips for each node. Selecting a
-composable node shows the dimensions and parameters of the composable, unless
-it's an inline function, in which case the parameters can't be shown. You can
-also see similar information in the **Attributes** pane when you select a
-composable from the **Component Tree** or the **Layout Display**.
+Open the **Layout Inspector** window and connect to your app process. In the **Component Tree** , there are two columns that appear next to the layout hierarchy. The first column shows the number of compositions for each node and the second column displays the number of skips for each node. Selecting a composable node shows the dimensions and parameters of the composable, unless it's an inline function, in which case the parameters can't be shown. You can also see similar information in the **Attributes** pane when you select a composable from the **Component Tree** or the **Layout Display**.
-Resetting the count can help you understand recompositions or skips during a
-specific interaction with your app. If you want to reset the count, click
-**Reset** near the top of the **Component Tree** pane.
+Resetting the count can help you understand recompositions or skips during a specific interaction with your app. If you want to reset the count, click **Reset** near the top of the **Component Tree** pane.
> [!NOTE]
> **Note:** If you don't see the new columns in the **Component Tree** pane, you can view them by selecting **Show Recomposition Counts** from the **View Options** menu  describe your UI in an
-alternative manner that is understandable for
-[Accessibility](https://developer.android.com/develop/ui/compose/accessibility) services and for the
-[Testing](https://developer.android.com/develop/ui/compose/testing) framework. You can use the Layout Inspector
-to inspect semantic information in your Compose layouts.
+In Compose, [Semantics](https://developer.android.com/develop/ui/compose/accessibility/semantics) describe your UI in an alternative manner that is understandable for [Accessibility](https://developer.android.com/develop/ui/compose/accessibility) services and for the [Testing](https://developer.android.com/develop/ui/compose/testing) framework. You can use the Layout Inspector to inspect semantic information in your Compose layouts.
 **Figure 4.** Semantic information displayed using the Layout Inspector.
-When selecting a Compose node, use the **Attributes** pane to check whether it
-declares semantic information directly, merges semantics from its children, or
-both. To quickly identify which nodes include semantics, either declared or
-merged, use select the **View options** drop-down in the **Component Tree** pane
-and select **Highlight Semantics Layers**. This highlights only the nodes in the
-tree that include semantics, and you can use your keyboard to quickly navigate
-between them.
+When selecting a Compose node, use the **Attributes** pane to check whether it declares semantic information directly, merges semantics from its children, or both. To quickly identify which nodes include semantics, either declared or merged, use select the **View options** drop-down in the **Component Tree** pane and select **Highlight Semantics Layers**. This highlights only the nodes in the tree that include semantics, and you can use your keyboard to quickly navigate between them.
## Compose UI Check
-To help you build more adaptive and accessible UIs in Jetpack Compose, Android
-Studio provides a UI Check mode in Compose Preview. This feature is similar
-to [Accessibility Scanner](https://developer.android.com/guide/topics/ui/accessibility/testing#accessibility-scanner)
-for views.
+To help you build more adaptive and accessible UIs in Jetpack Compose, Android Studio provides a UI Check mode in Compose Preview. This feature is similar to [Accessibility Scanner](https://developer.android.com/guide/topics/ui/accessibility/testing#accessibility-scanner) for views.
-When you activate Compose UI check mode on a Compose Preview, Android Studio
-automatically audits your Compose UI and suggests improvements to make your UI
-more accessible and adaptive. Android Studio checks that your UI works across
-different screen sizes. In the **Problems** panel, the tool shows the issues
-that it detects, such as text stretched on large screens or low color contrast.
+When you activate Compose UI check mode on a Compose Preview, Android Studio automatically audits your Compose UI and suggests improvements to make your UI more accessible and adaptive. Android Studio checks that your UI works across different screen sizes. In the **Problems** panel, the tool shows the issues that it detects, such as text stretched on large screens or low color contrast.
To access this feature, click the UI Check icon on Compose Preview:
 **Figure 5.** Entry point to UI check mode.
-UI check automatically previews your UI in different configurations and
-highlights issues found in different configurations. In the **Problems** panel,
-when you click an issue, you can see the details of the issue, suggested fixes,
-and the renderings that highlight the area of the issue.
+UI check automatically previews your UI in different configurations and highlights issues found in different configurations. In the **Problems** panel, when you click an issue, you can see the details of the issue, suggested fixes, and the renderings that highlight the area of the issue.
 **Figure 6.** UI check mode in action.
### Fix with AI
-For issues detected in UI Check mode, you can use the AI agent to propose and
-apply code fixes. Click the **Fix with AI** button on an issue in the
-**Problems** panel. The agent analyzes the problem and your code to suggest
-changes that resolve the accessibility or adaptive issue.
+For issues detected in UI Check mode, you can use the AI agent to propose and apply code fixes. Click the **Fix with AI** button on an issue in the **Problems** panel. The agent analyzes the problem and your code to suggest changes that resolve the accessibility or adaptive issue.
 **Figure 7.** The agent fixes UI issues in UI Check mode.
\ No newline at end of file
diff --git a/jetpack-compose/adaptive/references/android/guide/navigation/navigation-3/recipes/material-listdetail.md b/jetpack-compose/adaptive/references/android/guide/navigation/navigation-3/recipes/material-listdetail.md
index fbaae79..032a997 100644
--- a/jetpack-compose/adaptive/references/android/guide/navigation/navigation-3/recipes/material-listdetail.md
+++ b/jetpack-compose/adaptive/references/android/guide/navigation/navigation-3/recipes/material-listdetail.md
@@ -138,4 +138,6 @@ class MaterialListDetailActivity : ComponentActivity() {
}
}
}
+
+
```
\ No newline at end of file
diff --git a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/SKILL.md b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/SKILL.md
index ea25f8e..c51cc9d 100644
--- a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/SKILL.md
+++ b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/SKILL.md
@@ -9,7 +9,7 @@ description: Provides a structured workflow for migrating an Android XML View to
license: Complete terms in LICENSE.txt
metadata:
author: Google LLC
- last-updated: '2026-07-02'
+ last-updated: '2026-08-06'
keywords:
- Jetpack Compose
- migration
@@ -20,16 +20,11 @@ metadata:
- UI development
---
-This skill guides through the process of migrating an existing Android XML View
-to Jetpack Compose. It performs a stable, safe and visually consistent
-transition by following a structured, 10-step methodology. This skill migrates
-UI (XML to Jetpack Compose) only.
+This skill guides through the process of migrating an existing Android XML View to Jetpack Compose. It performs a stable, safe and visually consistent transition by following a structured, 10-step methodology. This skill migrates UI (XML to Jetpack Compose) only.
## Objective
-To systematically convert a single legacy XML layout into modern, declarative
-Jetpack Compose UI while maintaining pixel-perfect visual parity and functional
-integrity.
+To systematically convert a single legacy XML layout into modern, declarative Jetpack Compose UI while maintaining pixel-perfect visual parity and functional integrity.
## Summary of the 10-step migration process
@@ -48,61 +43,31 @@ integrity.
### Step 1: Identify the optimal XML candidate for migration
-If the user has explicitly specified a target XML layout, proceed to Step 2.
-Otherwise, analyze the codebase to identify the best candidate for migration by
-following the logic in [references/identify-optimal-xml-candidate.md](references/identify-optimal-xml-candidate.md).
+If the user has explicitly specified a target XML layout, proceed to Step 2. Otherwise, analyze the codebase to identify the best candidate for migration by following the logic in [references/identify-optimal-xml-candidate.md](references/identify-optimal-xml-candidate.md).
### Step 2: Analyze the project and layout
-Analyze the identified XML View's structure, hierarchy, and implementation
-details.
-Use [references/analysis-of-the-project-and-layout.md](references/analysis-of-the-project-and-layout.md) to
-guide your technical audit of the layout and surrounding project context.
+Analyze the identified XML View's structure, hierarchy, and implementation details. Use [references/analysis-of-the-project-and-layout.md](references/analysis-of-the-project-and-layout.md) to guide your technical audit of the layout and surrounding project context.
### Step 3: Create a plan
-Using the outputs and analysis done in the Step 1 and 2, generate a
-step-by-step plan for the migration. If you support user interaction, present
-to the user and ask for approval before proceeding. If user interaction is not
-supported, proceed to Step 4 following the generated plan.
+Using the outputs and analysis done in the Step 1 and 2, generate a step-by-step plan for the migration. If you support user interaction, present to the user and ask for approval before proceeding. If user interaction is not supported, proceed to Step 4 following the generated plan.
### Step 4: Capture the XML View UI
-**IF** you support user interaction, ask the user to upload a screenshot of the
-XML View UI or provide an absolute path to a file. Use this image as a visual
-reference for the layout migration in Step 7.
-**ELSE IF** you are able to run an Android emulator, locate an existing
-screenshot test for the XML candidate. If none exists, create one using the
-existing project testing framework. If no framework exists,
-use **UI Automator** or **Espresso** to create a screenshot test with minimum
-required setup. Run the test and take a baseline screenshot of the XML UI.
-**ELSE** proceed to Step 5.
+**IF** you support user interaction, ask the user to upload a screenshot of the XML View UI or provide an absolute path to a file. Use this image as a visual reference for the layout migration in Step 7. **ELSE IF** you are able to run an Android emulator, locate an existing screenshot test for the XML candidate. If none exists, create one using the existing project testing framework. If no framework exists, use **UI Automator** or **Espresso** to create a screenshot test with minimum required setup. Run the test and take a baseline screenshot of the XML UI. **ELSE** proceed to Step 5.
### Step 5: Set up Compose dependencies and compiler
-Check `build.gradle` or `libs.versions.toml` for Compose dependencies and
-compiler setup. If missing, use
-[Setup Compose Dependencies and Compiler](references/android/develop/ui/compose/setup-compose-dependencies-and-compiler.md).
-Run a sync to ensure dependencies resolve without errors.
+Check `build.gradle` or `libs.versions.toml` for Compose dependencies and compiler setup. If missing, use [Setup Compose Dependencies and Compiler](references/android/develop/ui/compose/setup-compose-dependencies-and-compiler.md). Run a sync to ensure dependencies resolve without errors.
### Step 6: Set up Compose theming
-If the project already has Compose theming set up, proceed to Step 7. If Compose
-theming is missing, initialize it. For Material-based projects, follow
-[Material 3 migration guidelines](references/android/develop/ui/compose/designsystems/migrate-xml-theme-to-compose.md).
-For custom design systems, apply expert judgment to migrate XML theming and
-match existing styles.
-**Constraints:** Do not migrate the entire theme. Implement only the minimum
-theming required for the specific XML candidate. Maintain original XML themes
-for interoperability. Maintain existing project code conventions, patterns,
-names and values.
+If the project already has Compose theming set up, proceed to Step 7. If Compose theming is missing, initialize it. For Material-based projects, follow [Material 3 migration guidelines](references/android/develop/ui/compose/designsystems/migrate-xml-theme-to-compose.md). For custom design systems, apply expert judgment to migrate XML theming and match existing styles. **Constraints:** Do not migrate the entire theme. Implement only the minimum theming required for the specific XML candidate. Maintain original XML themes for interoperability. Maintain existing project code conventions, patterns, names and values.
### Step 7: Migrate the XML View to Compose
-Convert the XML candidate to Jetpack Compose code, referencing
-[references/xml-layout-migration.md](references/xml-layout-migration.md) and the image from Step 4.
-You must include a **Compose Preview** for the newly created composable to
-facilitate visual verification.
+Convert the XML candidate to Jetpack Compose code, referencing [references/xml-layout-migration.md](references/xml-layout-migration.md) and the image from Step 4. You must include a **Compose Preview** for the newly created composable to facilitate visual verification.
### Step 8: Replace usages
@@ -113,12 +78,8 @@ Replace the usages of the migrated XML layout to use the new Compose component.
### Step 9: Validate the migration
-Compare the baseline screenshot image from Step 4 with the rendered Compose
-Preview of the new composable. Ignore string content; focus on layout and
-styling. Iterate on the Compose code until visual parity is achieved. Once
-verified, write a Compose UI test for the new composable.
+Compare the baseline screenshot image from Step 4 with the rendered Compose Preview of the new composable. Ignore string content; focus on layout and styling. Iterate on the Compose code until visual parity is achieved. Once verified, write a Compose UI test for the new composable.
### Step 10: XML code removal
-Delete the migrated XML file and its associated legacy tests. **Caution:** Only
-remove code and resources that are not referenced by other parts of the project.
+Delete the migrated XML file and its associated legacy tests. **Caution:** Only remove code and resources that are not referenced by other parts of the project.
diff --git a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/analysis-of-the-project-and-layout.md b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/analysis-of-the-project-and-layout.md
index 3e2f0c3..8b34a75 100644
--- a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/analysis-of-the-project-and-layout.md
+++ b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/analysis-of-the-project-and-layout.md
@@ -1,41 +1,22 @@
## 1. Project health \& build validation
-Before performing any analysis, you must confirm the project is in a functional state.
-\* **Integrity check:** Verify the project syncs (Gradle) and builds successfully.
-\* **Error resolution:** If there are pre-existing build errors or sync failures, you must report these immediately and attempt to fix. **Do not proceed** with migration until a stable baseline is established.
+Before performing any analysis, you must confirm the project is in a functional state. \* **Integrity check:** Verify the project syncs (Gradle) and builds successfully. \* **Error resolution:** If there are pre-existing build errors or sync failures, you must report these immediately and attempt to fix. **Do not proceed** with migration until a stable baseline is established.
## 2. Compose pattern \& consistency analysis
-If Jetpack Compose is already present, you must align with the established implementation style.
-\* **Pattern identification:** Scan the codebase for `@Composable` functions. Identify the project's "Best Practices" regarding state hoisting, composable construction and naming conventions, and file organization.
-\* **Theming review:** Determine how `MaterialTheme` or custom theme systems are implemented.
-\* Identify if the project uses a custom design system theme.
-\* Map how attributes, styles, and other theme components are accessed in Compose.
+If Jetpack Compose is already present, you must align with the established implementation style. \* **Pattern identification:** Scan the codebase for `@Composable` functions. Identify the project's "Best Practices" regarding state hoisting, composable construction and naming conventions, and file organization. \* **Theming review:** Determine how `MaterialTheme` or custom theme systems are implemented. \* Identify if the project uses a custom design system theme. \* Map how attributes, styles, and other theme components are accessed in Compose.
## 3. Design system \& infrastructure audit
-Understand the design system classification (e.g. Material 2, Material 3, or custom design system).
-\* **Resource mapping:** Locate central XML definitions:
-\* `colors.xml` (Light/Dark variants)
-\* `dimens.xml`
-\* `styles.xml` / `themes.xml`
-\* **Hybrid analysis:** Determine if the project is **XML-only** , **Compose-only** , or **Hybrid** .
-\* **Reuse constraint:** If a Compose theming layer (e.g., `AppTheme.kt`) already exists, **DO NOT** generate a new one. You must reuse the existing infrastructure and contribute to it by following its existing implementation pattern.
+Understand the design system classification (e.g. Material 2, Material 3, or custom design system). \* **Resource mapping:** Locate central XML definitions: \* `colors.xml` (Light/Dark variants) \* `dimens.xml` \* `styles.xml` / `themes.xml` \* **Hybrid analysis:** Determine if the project is **XML-only** , **Compose-only** , or **Hybrid** . \* **Reuse constraint:** If a Compose theming layer (e.g., `AppTheme.kt`) already exists, **DO NOT** generate a new one. You must reuse the existing infrastructure and contribute to it by following its existing implementation pattern.
## 4. Candidate layout decomposition
-Analyze the specific XML layout targeted for migration. You must extract and document the following requirements for the new composable:
-\* **Inputs:** UI State objects, primitive parameters, and click listeners.
-\* **Styling:** Specific color constants, typography styles, and shape definitions referenced in the XML.
-\* **Resources:** Identifying string resources, drawables, and dimensions.
-\* **Layout logic:** Modifiers required to replicate the XML constraints (padding, alignment, weight).
+Analyze the specific XML layout targeted for migration. You must extract and document the following requirements for the new composable: \* **Inputs:** UI State objects, primitive parameters, and click listeners. \* **Styling:** Specific color constants, typography styles, and shape definitions referenced in the XML. \* **Resources:** Identifying string resources, drawables, and dimensions. \* **Layout logic:** Modifiers required to replicate the XML constraints (padding, alignment, weight).
## 5. Architectural \& non-UI analysis
-Understand the environment in which the UI resides to ensure proper integration.
-\* **State management:** Identify the usage of `ViewModel`, `Flow`, or `LiveData`.
-\* **Dependency Injection:** Check for Hilt, Koin, or manual DI to understand how dependencies are provided to the UI layer.
-\* **Testing \& architecture:** Note the architectural pattern (MVI, MVVM, or custom architecture setup.) and existing UI testing frameworks to ensure the migrated code remains testable. Unless the user explicitly requests, **DO NOT** make any changes to any non-UI code that aren't strictly required for the migration of the XML View.
+Understand the environment in which the UI resides to ensure proper integration. \* **State management:** Identify the usage of `ViewModel`, `Flow`, or `LiveData`. \* **Dependency Injection:** Check for Hilt, Koin, or manual DI to understand how dependencies are provided to the UI layer. \* **Testing \& architecture:** Note the architectural pattern (MVI, MVVM, or custom architecture setup.) and existing UI testing frameworks to ensure the migrated code remains testable. Unless the user explicitly requests, **DO NOT** make any changes to any non-UI code that aren't strictly required for the migration of the XML View.
*** ** * ** ***
diff --git a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/designsystems/migrate-xml-theme-to-compose.md b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/designsystems/migrate-xml-theme-to-compose.md
index 60b7968..3eb0b20 100644
--- a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/designsystems/migrate-xml-theme-to-compose.md
+++ b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/designsystems/migrate-xml-theme-to-compose.md
@@ -1,14 +1,8 @@
-When you introduce Compose in an existing app, you need to migrate your Material
-XML themes to use `MaterialTheme` for Compose components. This means your app's
-theming will have two sources of truth: the View-based theme and the Compose
-theme. Any changes to your styling need to be made in multiple places. Once
-your app is fully migrated to Compose, remove your XML theming.
+When you introduce Compose in an existing app, you need to migrate your Material XML themes to use `MaterialTheme` for Compose components. This means your app's theming will have two sources of truth: the View-based theme and the Compose theme. Any changes to your styling need to be made in multiple places. Once your app is fully migrated to Compose, remove your XML theming.
-You can use the [Material Theme Builder](https://m3.material.io/theme-builder)
-tool for migrating colors.
+You can use the [Material Theme Builder](https://m3.material.io/theme-builder) tool for migrating colors.
-When you start the migration from XML to Compose, migrate the theming to
-Material 3 Compose theming.
+When you start the migration from XML to Compose, migrate the theming to Material 3 Compose theming.
## Glossary
@@ -29,26 +23,19 @@ Before migrating, be aware of the following limitations:
## Step 1: Evaluate the design system
-Identify which design system is used in the XML View project.
-Analyze the migration path and necessary steps to migrate the existing design
-system to Material 3 in Compose.
+Identify which design system is used in the XML View project. Analyze the migration path and necessary steps to migrate the existing design system to Material 3 in Compose.
## Step 2: Identify theme source files
-In XML you write `?attr/colorPrimary`. In Compose, you access theme values
-with `MaterialTheme.*`:
+In XML you write `?attr/colorPrimary`. In Compose, you access theme values with `MaterialTheme.*`:
-Identify and locate all XML resources and files necessary for theming:
-light and dark color schemes and qualifiers, themes, shapes, dimensions,
-typography, styles and other relevant files.
+Identify and locate all XML resources and files necessary for theming: light and dark color schemes and qualifiers, themes, shapes, dimensions, typography, styles and other relevant files.
Resources such as strings can be reused as is and don't need to be migrated.
## Step 3: Migrate colors
-**Key principle:** XML uses named hex colors.
-Material 3 uses *semantic roles* (e.g., `primary`, `onPrimary`, `surface`).
-Stop naming colors by their hex; name them by their role.
+**Key principle:** XML uses named hex colors. Material 3 uses *semantic roles* (e.g., `primary`, `onPrimary`, `surface`). Stop naming colors by their hex; name them by their role.
Examples:
@@ -69,8 +56,7 @@ Examples:
*** ** * ** ***
-Migrate the dark and light color schemes from XML to their equivalents in
-Material 3 Compose.
+Migrate the dark and light color schemes from XML to their equivalents in Material 3 Compose.
> [!NOTE]
> **Note:** Material 3 naming differs from Material 2 color naming.
@@ -117,20 +103,14 @@ XML styles (styles.xml) system defines styles and appearance of:
3. Themes and overlays
4. Shapes
-XML Views and components combine multiple attributes to create a style.
-They set their styles from styles.xml in two different ways:
+XML Views and components combine multiple attributes to create a style. They set their styles from styles.xml in two different ways:
1. Setting "style="@style/..." directly and explicitly in the XML View
2. Setting the style indirectly and implicitly for a component as part of a larger Theme (theme.xml)
-Styles have no **direct** equivalent in Compose - instead styles are passed as:
-parameters or modifiers to composables, using the
-[new, experimental Styles API](https://developer.android.com/develop/ui/compose/styles) defined in the AppTheme, or by creating
-layered, reusable composable variations with the defined style.
+Styles have no **direct** equivalent in Compose - instead styles are passed as: parameters or modifiers to composables, using the [new, experimental Styles API](https://developer.android.com/develop/ui/compose/styles) defined in the AppTheme, or by creating layered, reusable composable variations with the defined style.
-Provide separate @Composable functions named according to the style and the
-base component, to signify the difference in styling and use cases for those
-components.
+Provide separate @Composable functions named according to the style and the base component, to signify the difference in styling and use cases for those components.
- **Pattern:** If an XML element uses a custom style (e.g., `style="@style/MyPrimaryButton"`), don't try to replicate the style inline. Instead, suggest creating a specific composable.
- **Example:**
@@ -162,10 +142,6 @@ components.
## Step 6: Validate the theme migration
-Always use the existing theme values from the original XML theme as the source
-of truth for the new Material Theme in Compose.
-Never invent new theme values during migration, to maintain brand consistency
-and avoid visual regressions.
+Always use the existing theme values from the original XML theme as the source of truth for the new Material Theme in Compose. Never invent new theme values during migration, to maintain brand consistency and avoid visual regressions.
-Verify all new Compose theme values match the existing XML values.
-Don't hardcode any migrated values.
\ No newline at end of file
+Verify all new Compose theme values match the existing XML values. Don't hardcode any migrated values.
\ No newline at end of file
diff --git a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/migrate/interoperability-apis/compose-in-views.md b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/migrate/interoperability-apis/compose-in-views.md
index 83c7188..a0bc6ad 100644
--- a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/migrate/interoperability-apis/compose-in-views.md
+++ b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/migrate/interoperability-apis/compose-in-views.md
@@ -3,10 +3,9 @@
You can add Compose-based UI into an existing app that uses a View-based design.
-To create a new, entirely Compose-based screen, have your
-activity call the `setContent()` method, and pass whatever composable functions
-you like.
+To create a new, entirely Compose-based screen, have your activity call the `setContent()` method, and pass whatever composable functions you like.
+
```kotlin
class ExampleActivity : ComponentActivity() {
@@ -25,6 +24,7 @@ class ExampleActivity : ComponentActivity() {
fun Greeting(name: String) {
Text(text = "Hello $name!")
}
+
```
@@ -32,30 +32,17 @@ fun Greeting(name: String) {
This code looks just like what you'd find in a Compose-only app.
> [!CAUTION]
-> **Caution:** To use the `ComponentActivity.setContent`
-> method, add the `androidx.activity:activity-compose:$latestVersion`
-> dependency to your `build.gradle` file.
+> **Caution:** To use the `ComponentActivity.setContent` method, add the `androidx.activity:activity-compose:$latestVersion` dependency to your `build.gradle` file.
>
-> See the [Activity releases page](https://developer.android.com/jetpack/androidx/releases/activity)
-> to find out the latest version.
+> See the [Activity releases page](https://developer.android.com/jetpack/androidx/releases/activity) to find out the latest version.
## `ViewCompositionStrategy` for `ComposeView`
-[`ViewCompositionStrategy`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/ViewCompositionStrategy)
-defines when the Composition should be disposed. The default,
-[`ViewCompositionStrategy.Default`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/ViewCompositionStrategy#Default()),
-disposes the Composition when the underlying
-[`ComposeView`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/ComposeView)
-detaches from the window, unless it is part of a pooling container such as a
-`RecyclerView`. In a single-Activity Compose-only app, this default behavior is
-what you would want, however, if you are incrementally adding Compose in your
-codebase, this behavior may cause state loss in some scenarios.
+[`ViewCompositionStrategy`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/ViewCompositionStrategy) defines when the Composition should be disposed. The default, [`ViewCompositionStrategy.Default`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/ViewCompositionStrategy#Default()), disposes the Composition when the underlying [`ComposeView`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/ComposeView) detaches from the window, unless it is part of a pooling container such as a `RecyclerView`. In a single-Activity Compose-only app, this default behavior is what you would want, however, if you are incrementally adding Compose in your codebase, this behavior may cause state loss in some scenarios.
-To change the `ViewCompositionStrategy`, call the [`setViewCompositionStrategy()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/AbstractComposeView#setViewCompositionStrategy(androidx.compose.ui.platform.ViewCompositionStrategy))
-method and provide a different strategy.
+To change the `ViewCompositionStrategy`, call the [`setViewCompositionStrategy()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/AbstractComposeView#setViewCompositionStrategy(androidx.compose.ui.platform.ViewCompositionStrategy)) method and provide a different strategy.
-The table below summarizes the different scenarios you can use
-`ViewCompositionStrategy` in:
+The table below summarizes the different scenarios you can use `ViewCompositionStrategy` in:
| `ViewCompositionStrategy` | Description and Interop Scenario |
|---|---|
@@ -69,11 +56,7 @@ The table below summarizes the different scenarios you can use
> [!NOTE]
> **Note:** For hybrid apps with Views and Compose, that use Fragments, use `ComposeView` to wrap composables content and add to a Fragment during migration. For Compose-only apps, do not use Fragments and instead use the recommended Compose-only architecture with a single Activity and latest navigation libraries, like Navigation 3.
-If you want to incorporate Compose UI content in a fragment or an existing View
-layout, use [`ComposeView`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/ComposeView)
-and call its
-[`setContent()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/ComposeView#setContent(kotlin.Function0))
-method. `ComposeView` is an Android [`View`](https://developer.android.com/reference/android/view/View).
+If you want to incorporate Compose UI content in a fragment or an existing View layout, use [`ComposeView`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/ComposeView) and call its [`setContent()`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/ComposeView#setContent(kotlin.Function0)) method. `ComposeView` is an Android [`View`](https://developer.android.com/reference/android/view/View).
You can put the `ComposeView` in your XML layout just like any other `View`:
@@ -93,13 +76,12 @@ You can put the `ComposeView` in your XML layout just like any other `View`:
android:layout_width="match_parent"
android:layout_height="match_parent" />
+
```
-In the Kotlin source code, inflate the layout from the [layout
-resource](https://developer.android.com/guide/topics/resources/layout-resource) defined in XML. Then get the
-`ComposeView` using the XML ID, set a Composition strategy that works best for
-the host `View`, and call `setContent()` to use Compose.
+In the Kotlin source code, inflate the layout from the [layout resource](https://developer.android.com/guide/topics/resources/layout-resource) defined in XML. Then get the `ComposeView` using the XML ID, set a Composition strategy that works best for the host `View`, and call `setContent()` to use Compose.
+
```kotlin
class ExampleFragmentXml : Fragment() {
@@ -125,13 +107,14 @@ class ExampleFragmentXml : Fragment() {
return view
}
}
+
```
-Alternatively, you can also use view binding to obtain references to the
-`ComposeView` by referencing the generated binding class for your XML layout file:
+Alternatively, you can also use view binding to obtain references to the `ComposeView` by referencing the generated binding class for your XML layout file:
+
```kotlin
class ExampleFragment : Fragment() {
@@ -167,20 +150,18 @@ class ExampleFragment : Fragment() {
_binding = null
}
}
+
```

-**Figure 1.** This shows the output of the code that adds Compose elements in a
-View UI hierarchy. The "Hello Android!" text is displayed by a
-`TextView` widget. The "Hello Compose!" text is displayed by a
-Compose text element.
+**Figure 1.** This shows the output of the code that adds Compose elements in a View UI hierarchy. The "Hello Android!" text is displayed by a `TextView` widget. The "Hello Compose!" text is displayed by a Compose text element.
-You can also include a `ComposeView` directly in a fragment if your full screen
-is built with Compose, which lets you avoid using an XML layout file entirely.
+You can also include a `ComposeView` directly in a fragment if your full screen is built with Compose, which lets you avoid using an XML layout file entirely.
+
```kotlin
class ExampleFragmentNoXml : Fragment() {
@@ -203,15 +184,16 @@ class ExampleFragmentNoXml : Fragment() {
}
}
}
+
```
## Multiple `ComposeView` instances in the same layout
-If there are multiple `ComposeView` elements in the same layout, each one must
-have a unique ID for `savedInstanceState` to work.
+If there are multiple `ComposeView` elements in the same layout, each one must have a unique ID for `savedInstanceState` to work.
+
```kotlin
class ExampleFragmentMultipleComposeView : Fragment() {
@@ -242,6 +224,7 @@ class ExampleFragmentMultipleComposeView : Fragment() {
)
}
}
+
```
@@ -253,18 +236,16 @@ The `ComposeView` IDs are defined in the `res/values/ids.xml` file:
+
```
## Preview composables in Layout Editor
-You can also preview composables within the Layout Editor for your XML layout
-containing a `ComposeView`. Doing so lets you see how your composables look
-within a mixed Views and Compose layout.
+You can also preview composables within the Layout Editor for your XML layout containing a `ComposeView`. Doing so lets you see how your composables look within a mixed Views and Compose layout.
-Say you want to display the following composable in the Layout Editor. Note
-that composables annotated with `@Preview` are good candidates to preview in the
-Layout Editor.
+Say you want to display the following composable in the Layout Editor. Note that composables annotated with `@Preview` are good candidates to preview in the Layout Editor.
+
```kotlin
@Preview
@@ -272,13 +253,12 @@ Layout Editor.
fun GreetingPreview() {
Greeting(name = "Android")
}
+
```
-To display this composable, use the `tools:composableName` tools attribute and
-set its value to the fully qualified name of the composable to preview in the
-layout.
+To display this composable, use the `tools:composableName` tools attribute and set its value to the fully qualified name of the composable to preview in the layout.
```xml
+
```

\ No newline at end of file
diff --git a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/migrate/interoperability-apis/views-in-compose.md b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/migrate/interoperability-apis/views-in-compose.md
index 14b9121..248d909 100644
--- a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/migrate/interoperability-apis/views-in-compose.md
+++ b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/migrate/interoperability-apis/views-in-compose.md
@@ -1,22 +1,13 @@
-You can include an Android View hierarchy in a Compose UI. This approach is
-particularly useful if you want to use UI elements that are not yet available in
-Compose, like
-[`AdView`](https://developers.google.com/android/reference/com/google/android/gms/ads/AdView).
-This approach also lets you reuse custom views you may have designed.
+You can include an Android View hierarchy in a Compose UI. This approach is particularly useful if you want to use UI elements that are not yet available in Compose, like [`AdView`](https://developers.google.com/android/reference/com/google/android/gms/ads/AdView). This approach also lets you reuse custom views you may have designed.
> [!NOTE]
> **Note:** Use `AndroidView` as a wrapper only for missing SDK components without Compose support. Rewrite your custom Views in Compose wherever possible, starting the migration with the simplest custom Views and scaling to more complex ones.
-To include a view element or hierarchy, use the [`AndroidView`](https://developer.android.com/reference/kotlin/androidx/compose/ui/viewinterop/AndroidView.composable#AndroidView(kotlin.Function1,androidx.compose.ui.Modifier,kotlin.Function1))
-composable. `AndroidView` is passed a lambda that returns a
-[`View`](https://developer.android.com/reference/android/view/View). `AndroidView` also provides an `update`
-callback that is called when the view is inflated. The `AndroidView` recomposes
-whenever a `State` read within the callback changes. `AndroidView`, like many
-other built-in composables, takes a `Modifier` parameter that can be used, for
-example, to set its position in the parent composable.
+To include a view element or hierarchy, use the [`AndroidView`](https://developer.android.com/reference/kotlin/androidx/compose/ui/viewinterop/AndroidView.composable#AndroidView(kotlin.Function1,androidx.compose.ui.Modifier,kotlin.Function1)) composable. `AndroidView` is passed a lambda that returns a [`View`](https://developer.android.com/reference/android/view/View). `AndroidView` also provides an `update` callback that is called when the view is inflated. The `AndroidView` recomposes whenever a `State` read within the callback changes. `AndroidView`, like many other built-in composables, takes a `Modifier` parameter that can be used, for example, to set its position in the parent composable.
+
```kotlin
@Composable
@@ -54,6 +45,8 @@ fun ContentExample() {
CustomView()
}
}
+
+
```
@@ -63,14 +56,12 @@ fun ContentExample() {
## `AndroidView` with view binding
-To embed an XML layout, use the
-[`AndroidViewBinding`](https://developer.android.com/reference/kotlin/androidx/compose/ui/viewinterop/package-summary#AndroidViewBinding(kotlin.Function3,%20androidx.compose.ui.Modifier,%20kotlin.Function1))
-API, which is provided by the `androidx.compose.ui:ui-viewbinding` library. To
-do this, your project must enable [view binding](https://developer.android.com/topic/libraries/view-binding#setup).
+To embed an XML layout, use the [`AndroidViewBinding`](https://developer.android.com/reference/kotlin/androidx/compose/ui/viewinterop/package-summary#AndroidViewBinding(kotlin.Function3,%20androidx.compose.ui.Modifier,%20kotlin.Function1)) API, which is provided by the `androidx.compose.ui:ui-viewbinding` library. To do this, your project must enable [view binding](https://developer.android.com/topic/libraries/view-binding#setup).
> [!NOTE]
> **Note:** For Compose-only apps, don't use `AndroidViewBinding` to inflate full screen-level XML layouts, and instead use it only for smaller, legacy XML layouts during the incremental migration process.
+
```kotlin
@Composable
@@ -79,23 +70,21 @@ fun AndroidViewBindingExample() {
exampleView.setBackgroundColor(Color.GRAY)
}
}
+
```
## `AndroidView` in Lazy lists
-If you are using an `AndroidView` in a Lazy list (`LazyColumn`, `LazyRow`,
-`Pager`, etc.), consider using the [`AndroidView`](https://developer.android.com/reference/kotlin/androidx/compose/ui/viewinterop/package-summary#AndroidView(kotlin.Function1,kotlin.Function1,androidx.compose.ui.Modifier,kotlin.Function1,kotlin.Function1))
-overload introduced in version 1.4.0-rc01. This overload allows Compose to reuse
-the underlying `View` instance when the containing composition is reused as is
-the case for Lazy lists.
+If you are using an `AndroidView` in a Lazy list (`LazyColumn`, `LazyRow`, `Pager`, etc.), consider using the [`AndroidView`](https://developer.android.com/reference/kotlin/androidx/compose/ui/viewinterop/package-summary#AndroidView(kotlin.Function1,kotlin.Function1,androidx.compose.ui.Modifier,kotlin.Function1,kotlin.Function1)) overload introduced in version 1.4.0-rc01. This overload allows Compose to reuse the underlying `View` instance when the containing composition is reused as is the case for Lazy lists.
This overload of `AndroidView` adds 2 additional parameters:
- `onReset` - A callback invoked to signal that the `View` is about to be reused. This must be non-null to enable View reuse.
- `onRelease` (optional) - A callback invoked to signal that the `View` has exited the composition and will not be reused again.
+
```kotlin
@Composable
@@ -117,72 +106,50 @@ fun AndroidViewInLazyList() {
}
}
}
+
```
## Fragments in Compose (Transitionary Step)
-Use the `AndroidFragment` composable to add a `Fragment` in Compose.
-`AndroidFragment` has fragment-specific handling such as removing the
-fragment when the composable leaves the composition.
+Use the `AndroidFragment` composable to add a `Fragment` in Compose. `AndroidFragment` has fragment-specific handling such as removing the fragment when the composable leaves the composition.
> [!NOTE]
> **Note:** Wrap existing Fragments in Compose only during incremental migration. For Compose-only apps, do not use Fragments and instead use the recommended Compose-only architecture with a single Activity and latest navigation libraries, like Navigation 3.
-To include a fragment, use the [`AndroidFragment`](https://developer.android.com/reference/kotlin/androidx/fragment/compose/package-summary#AndroidFragment)
-composable. You pass a `Fragment` class to `AndroidFragment`, which then adds
-an instance of that class directly into the composition. `AndroidFragment` also
-provides a `fragmentState` object to create the `AndroidFragment` with a given
-state, `arguments` to pass into the new fragment, and an `onUpdate` callback
-that provides the fragment from the composition. Like many
-other built-in composables, `AndroidFragment` accepts a `Modifier` parameter
-that you can use, for
-example, to set its position in the parent composable.
+To include a fragment, use the [`AndroidFragment`](https://developer.android.com/reference/kotlin/androidx/fragment/compose/package-summary#AndroidFragment) composable. You pass a `Fragment` class to `AndroidFragment`, which then adds an instance of that class directly into the composition. `AndroidFragment` also provides a `fragmentState` object to create the `AndroidFragment` with a given state, `arguments` to pass into the new fragment, and an `onUpdate` callback that provides the fragment from the composition. Like many other built-in composables, `AndroidFragment` accepts a `Modifier` parameter that you can use, for example, to set its position in the parent composable.
Call `AndroidFragment` in Compose as follows:
+
```kotlin
@Composable
fun FragmentInComposeExample() {
AndroidFragment()
}
+
+
```
## Calling the Android framework from Compose
-Compose operates within the Android framework classes. For example, it's hosted
-on Android View classes, like `Activity` or `Fragment`, and might use Android
-framework classes like the `Context`, system resources,
-`Service`, or `BroadcastReceiver`.
+Compose operates within the Android framework classes. For example, it's hosted on Android View classes, like `Activity` or `Fragment`, and might use Android framework classes like the `Context`, system resources, `Service`, or `BroadcastReceiver`.
To learn more about system resources, see [Resources in Compose](https://developer.android.com/develop/ui/compose/resources).
### Composition Locals
-[`CompositionLocal`](https://developer.android.com/reference/kotlin/androidx/compose/runtime/CompositionLocal)
-classes allow passing data implicitly through composable functions. They're
-usually provided with a value in a certain node of the UI tree. That value can
-be used by its composable descendants without declaring the `CompositionLocal`
-as a parameter in the composable function.
+[`CompositionLocal`](https://developer.android.com/reference/kotlin/androidx/compose/runtime/CompositionLocal) classes allow passing data implicitly through composable functions. They're usually provided with a value in a certain node of the UI tree. That value can be used by its composable descendants without declaring the `CompositionLocal` as a parameter in the composable function.
-`CompositionLocal` is used to propagate values for Android framework types in
-Compose such as `Context`, `Configuration` or the `View` in which the Compose
-code is hosted with the corresponding
-[`LocalContext`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/package-summary#LocalContext()),
-[`LocalConfiguration`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/package-summary#LocalConfiguration()),
-or
-[`LocalView`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/package-summary#LocalView()).
-Note that `CompositionLocal` classes are prefixed with `Local` for better
-discoverability with auto-complete in the IDE.
+`CompositionLocal` is used to propagate values for Android framework types in Compose such as `Context`, `Configuration` or the `View` in which the Compose code is hosted with the corresponding [`LocalContext`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/package-summary#LocalContext()), [`LocalConfiguration`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/package-summary#LocalConfiguration()), or [`LocalView`](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/package-summary#LocalView()). Note that `CompositionLocal` classes are prefixed with `Local` for better discoverability with auto-complete in the IDE.
-Access the current value of a `CompositionLocal` by using its `current`
-property. For example, the code below shows a toast message by providing
-`LocalContext.current` into the `Toast.makeToast` method.
+Access the current value of a `CompositionLocal` by using its `current` property. For example, the code below shows a toast message by providing `LocalContext.current` into the `Toast.makeToast` method.
+
```kotlin
@Composable
@@ -194,18 +161,16 @@ fun ToastGreetingButton(greeting: String) {
Text("Greet")
}
}
+
```
### Broadcast receivers
-To showcase `CompositionLocal` and [side
-effects](https://developer.android.com/develop/ui/compose/side-effects), if a
-[`BroadcastReceiver`](https://developer.android.com/guide/components/broadcasts) needs to be registered from
-a composable function, use of `LocalContext` to use the current context, and
-`rememberUpdatedState` and `DisposableEffect` side effects.
+To showcase `CompositionLocal` and [side effects](https://developer.android.com/develop/ui/compose/side-effects), if a [`BroadcastReceiver`](https://developer.android.com/guide/components/broadcasts) needs to be registered from a composable function, use of `LocalContext` to use the current context, and `rememberUpdatedState` and `DisposableEffect` side effects.
+
```kotlin
@Composable
@@ -247,18 +212,16 @@ fun HomeScreen() {
/* Rest of the HomeScreen */
}
+
```
## Other interactions
-If there isn't a utility defined for the interaction you need, the best practice
-is to follow the general Compose guideline,
-*data flows down, events flow up* (discussed at more length in [Thinking
-in Compose](https://developer.android.com/develop/ui/compose/mental-model)). For example, this composable
-launches a different activity:
+If there isn't a utility defined for the interaction you need, the best practice is to follow the general Compose guideline, *data flows down, events flow up* (discussed at more length in [Thinking in Compose](https://developer.android.com/develop/ui/compose/mental-model)). For example, this composable launches a different activity:
+
```kotlin
class OtherInteractionsActivity : ComponentActivity() {
@@ -281,6 +244,7 @@ fun ExampleComposable(data: DataExample, onButtonClick: () -> Unit) {
Text(data.title)
}
}
+
```
\ No newline at end of file
diff --git a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/setup-compose-dependencies-and-compiler.md b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/setup-compose-dependencies-and-compiler.md
index bf06fa0..ceda68a 100644
--- a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/setup-compose-dependencies-and-compiler.md
+++ b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/android/develop/ui/compose/setup-compose-dependencies-and-compiler.md
@@ -1,9 +1,7 @@
-For Gradle, use the Compose Compiler Gradle plugin to set up and configure
-Compose.
+For Gradle, use the Compose Compiler Gradle plugin to set up and configure Compose.
> [!NOTE]
-> **Note:** The Compose Compiler Gradle Plugin is only available from Kotlin 2.0+. For migration instructions, see ["Jetpack Compose compiler moving to the Kotlin
-> repository"](https://android-developers.googleblog.com/2024/04/jetpack-compose-compiler-moving-to-kotlin-repository.html).
+> **Note:** The Compose Compiler Gradle Plugin is only available from Kotlin 2.0+. For migration instructions, see ["Jetpack Compose compiler moving to the Kotlin repository"](https://android-developers.googleblog.com/2024/04/jetpack-compose-compiler-moving-to-kotlin-repository.html).
### Set up with Gradle version catalogs
@@ -21,8 +19,7 @@ Set up the Compose Compiler Gradle plugin:
// Add this line
compose-compiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
-3. In the project's root `build.gradle.kts` file, add the following to the
- `plugins` section.
+3. In the project's root `build.gradle.kts` file, add the following to the `plugins` section.
plugins {
// Existing plugins
@@ -36,14 +33,11 @@ Set up the Compose Compiler Gradle plugin:
alias(libs.plugins.compose.compiler)
}
-The project should now build and compile if it was using the default set up. If
-it had configured custom options on the Compose compiler, follow the next
-section.
+The project should now build and compile if it was using the default set up. If it had configured custom options on the Compose compiler, follow the next section.
### Set up the Compose Compiler without Gradle version catalogs
-Add the plugin to `build.gradle.kts` files associated with modules where Compose
-is used:
+Add the plugin to `build.gradle.kts` files associated with modules where Compose is used:
plugins {
id("org.jetbrains.kotlin.plugin.compose") version "2.3.21" // this version matches your Kotlin version
@@ -59,9 +53,7 @@ Add the classpath to your top-level project `build.gradle.kts` file:
### Configuration options with the Compose Compiler Gradle Plugin
-To configure the Compose compiler using the Gradle plugin, add the
-`composeCompiler` block to the module's `build.gradle.kts` file at the top
-level:
+To configure the Compose compiler using the Gradle plugin, add the `composeCompiler` block to the module's `build.gradle.kts` file at the top level:
android { ... }
@@ -74,10 +66,9 @@ For the full list of available options, see the [documentation](https://www.jetb
## Set up Compose dependencies
-Always use the latest Compose BOM version: `2026.06.00`.
+Always use the latest Compose BOM version: `2026.06.01`.
-Set the `compose` flag to `true` inside the Android [`BuildFeatures`](https://developer.android.com/reference/tools/gradle-api/7.0/com/android/build/api/dsl/BuildFeatures) to
-enable [Compose functionality](https://developer.android.com/develop/ui/compose/tooling) in Android Studio.
+Set the `compose` flag to `true` inside the Android [`BuildFeatures`](https://developer.android.com/reference/tools/gradle-api/7.0/com/android/build/api/dsl/BuildFeatures) to enable [Compose functionality](https://developer.android.com/develop/ui/compose/tooling) in Android Studio.
Add the following definition to your app's `build.gradle` file:
@@ -103,7 +94,7 @@ Add the Compose BOM and the subset of Compose library dependencies:
dependencies {
- def composeBom = platform('androidx.compose:compose-bom:2026.06.00')
+ def composeBom = platform('androidx.compose:compose-bom:2026.06.01')
implementation composeBom
androidTestImplementation composeBom
@@ -142,7 +133,7 @@ Add the Compose BOM and the subset of Compose library dependencies:
dependencies {
- val composeBom = platform("androidx.compose:compose-bom:2026.06.00")
+ val composeBom = platform("androidx.compose:compose-bom:2026.06.01")
implementation(composeBom)
androidTestImplementation(composeBom)
@@ -178,20 +169,12 @@ Add the Compose BOM and the subset of Compose library dependencies:
}
> [!NOTE]
-> **Note:** Jetpack Compose is shipped using a Bill of Materials (BOM), to keep the versions of all library groups in sync. Read more about it in the [Bill of
-> Materials page](https://developer.android.com/develop/ui/compose/bom/bom).
+> **Note:** Jetpack Compose is shipped using a Bill of Materials (BOM), to keep the versions of all library groups in sync. Read more about it in the [Bill of Materials page](https://developer.android.com/develop/ui/compose/bom/bom).
## `compileSdk` and Android Gradle Plugin compatibility
-Compose library releases continually adopt the latest `compileSdk` versions to
-provide access to the latest Android features. Newer `compileSdk` versions
-require newer versions of Android Gradle Plugin, so adopting new Compose
-releases also requires projects to adopt new versions of the Android Gradle
-Plugin. We recommend keeping your project's `compileSdk` up to date with the
-latest released versions. `compileSdk` is unrelated from `targetSdk`.
+Compose library releases continually adopt the latest `compileSdk` versions to provide access to the latest Android features. Newer `compileSdk` versions require newer versions of Android Gradle Plugin, so adopting new Compose releases also requires projects to adopt new versions of the Android Gradle Plugin. We recommend keeping your project's `compileSdk` up to date with the latest released versions. `compileSdk` is unrelated from `targetSdk`.
-For example, starting with Compose 1.12.0, projects are required to use
-`compileSdk 37` and Android Gradle Plugin (AGP) 9.
+For example, starting with Compose 1.12.0, projects are required to use `compileSdk 37` and Android Gradle Plugin (AGP) 9.
-To check which version of AGP is supported for different API levels, see the
-[Android Gradle plugin API level support](https://developer.android.com/build/releases/about-agp#api-level-support) documentation.
\ No newline at end of file
+To check which version of AGP is supported for different API levels, see the [Android Gradle plugin API level support](https://developer.android.com/build/releases/about-agp#api-level-support) documentation.
\ No newline at end of file
diff --git a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/identify-optimal-xml-candidate.md b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/identify-optimal-xml-candidate.md
index 650ac92..e8a42d0 100644
--- a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/identify-optimal-xml-candidate.md
+++ b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/identify-optimal-xml-candidate.md
@@ -14,18 +14,12 @@ Prioritize layouts that meet the following criteria:
### 3. Risk assessment
-Evaluate the migration risk based on:
-\* **Reusability:** Find layouts with **minimum reuse** across the project to limit regression impact.
-\* **Accessibility:** Ensure the layout has an **easily accessible entry point** (e.g., used in a simple Activity, Fragment, or as a standalone include).
+Evaluate the migration risk based on: \* **Reusability:** Find layouts with **minimum reuse** across the project to limit regression impact. \* **Accessibility:** Ensure the layout has an **easily accessible entry point** (e.g., used in a simple Activity, Fragment, or as a standalone include).
*** ** * ** ***
## Output requirements
-Provide a ranked list of the top 3-5 candidates. For each candidate, include:
-1. **File path:** (e.g., `res/layout/item_user_profile.xml`)
-2. **Rationale:** Why this is a good candidate based on the provided criteria.
-3. **Complexity score:** A rating from 1-5 (1 being simplest).
-4. **Dependency count:** List of custom/external views found within.
+Provide a ranked list of the top 3-5 candidates. For each candidate, include: 1. **File path:** (e.g., `res/layout/item_user_profile.xml`) 2. **Rationale:** Why this is a good candidate based on the provided criteria. 3. **Complexity score:** A rating from 1-5 (1 being simplest). 4. **Dependency count:** List of custom/external views found within.
**Action:** If you support user interaction, ask the user to choose which XML to proceed with. Else proceed with the best option, based on the previous criteria.
\ No newline at end of file
diff --git a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/xml-layout-migration.md b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/xml-layout-migration.md
index 5aeb6b3..ba27ac4 100644
--- a/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/xml-layout-migration.md
+++ b/jetpack-compose/migration/migrate-xml-views-to-jetpack-compose/references/xml-layout-migration.md
@@ -1,7 +1,6 @@
## 1. Structural analysis \& mapping
-**Identify the precise mapping** between XML elements and Compose equivalents.
-You must determine:
+**Identify the precise mapping** between XML elements and Compose equivalents. You must determine:
- The exact `@Composable` functions (e.g., `ConstraintLayout`, `Column`, `LazyColumn`) that replace the XML tag hierarchy.
- The specific parameters and `Modifier` extensions required to replicate XML attributes (e.g., `layout_width`, `padding`, `elevation`).
@@ -9,9 +8,7 @@ You must determine:
## 2. Migration execution
-**Convert the XML layout code to Jetpack Compose**, ensuring the visual
-hierarchy and layout logic are preserved while leveraging Compose's declarative
-nature.
+**Convert the XML layout code to Jetpack Compose**, ensuring the visual hierarchy and layout logic are preserved while leveraging Compose's declarative nature.
## 3. Theming \& design system integrity
@@ -23,8 +20,7 @@ nature.
## 4. Component layering \& reusability
-Evaluate if the XML layout serves as a foundation-level design system component
-(reused across the app with a distinct role). If it is:
+Evaluate if the XML layout serves as a foundation-level design system component (reused across the app with a distinct role). If it is:
- **Create a reusable composable:** Do not just inline the code. Define a new standalone `@Composable`.
- **Parameterization:** Expose specific parameters for variable data (text, colors, styles) and use `Modifier` for layout-specific customizations.
@@ -44,6 +40,7 @@ Example before migration:
Example after migration:
+
```kotlin
@Composable
@@ -73,6 +70,7 @@ fun RoundedBorderlessButton(
)
}
}
+
```
diff --git a/jetpack-compose/theming/styles/SKILL.md b/jetpack-compose/theming/styles/SKILL.md
index c223382..eb97976 100644
--- a/jetpack-compose/theming/styles/SKILL.md
+++ b/jetpack-compose/theming/styles/SKILL.md
@@ -8,7 +8,7 @@ description: Use this skill to integrate the Jetpack Compose Styles API into an
license: Complete terms in LICENSE.txt
metadata:
author: Google LLC
- last-updated: '2026-07-07'
+ last-updated: '2026-08-06'
keywords:
- Jetpack Compose
- Styles
@@ -30,13 +30,11 @@ metadata:
- The project must use `compileSdk` version 37 or higher.
- The project must use `androidx.compose.foundation:foundation` version `1.12.0-alpha01` or higher.
- Alternatively, the project must use Compose BOM version `2026.04.01` or higher.
-- The API requires this exact package: `import
- androidx.compose.foundation.style.Style`
+- The API requires this exact package: `import androidx.compose.foundation.style.Style`
### 2. Configure compiler options to enable experimental API
-You must opt-in to the experimental API at the project level. Add the following
-block to your module's `build.gradle.kts`:
+You must opt-in to the experimental API at the project level. Add the following block to your module's `build.gradle.kts`:
kotlin {
compilerOptions {
@@ -49,12 +47,9 @@ block to your module's `build.gradle.kts`:
Refer to the official documentation to complete specific development tasks:
-- Basic Style Usage: To set backgrounds, sizes, and alignments on a component, follow the [Compose Styles Fundamentals
- Guide](references/android/develop/ui/compose/styles/fundamentals.md).
-- State and Transitions: To configure property changes for state shifts (like pressed or hovered), follow the [Animations and State-Based Styling
- Guide](references/android/develop/ui/compose/styles/state-animations.md).
-- Architecture Trade offs: To decide when to use a Style versus a standard Modifier, follow the [Styles versus Modifiers
- Comparison](references/android/develop/ui/compose/styles/styles-vs-modifiers.md).
+- Basic Style Usage: To set backgrounds, sizes, and alignments on a component, follow the [Compose Styles Fundamentals Guide](references/android/develop/ui/compose/styles/fundamentals.md).
+- State and Transitions: To configure property changes for state shifts (like pressed or hovered), follow the [Animations and State-Based Styling Guide](references/android/develop/ui/compose/styles/state-animations.md).
+- Architecture Trade offs: To decide when to use a Style versus a standard Modifier, follow the [Styles versus Modifiers Comparison](references/android/develop/ui/compose/styles/styles-vs-modifiers.md).
- Theme Level Integration: To connect style definitions with custom themes, follow [Theming with Styles](references/android/develop/ui/compose/styles/theming.md) and [Custom Themes in Compose](references/android/develop/ui/compose/designsystems/custom.md).
## Step-by-Step Migration Workflow
@@ -71,6 +66,7 @@ Refer to the official documentation to complete specific development tasks:
1. Create a new file named `ComponentStyles.kt` in your theme directory.
2. Define a top-level data class to hold your component styles, for example, the Jetsnack one is called `JetsnackStyles`:
+
```kotlin
object ExampleComponentStyles {
@@ -81,13 +77,14 @@ Refer to the official documentation to complete specific development tasks:
}
}
+
```
-3. Expose this class through your custom theme with a static reference, don't
- use `CompositionLocals` here as it's not required.
+3. Expose this class through your custom theme with a static reference, don't use `CompositionLocals` here as it's not required.
+
```kotlin
@Immutable
@@ -104,13 +101,14 @@ Refer to the official documentation to complete specific development tasks:
val styles: ComponentStyles = ComponentStyles
}
}
+
```
-4. Provide extensions on `StyleScope` to reference theme tokens directly if
- they are exposed using `CompositionLocals`. For example:
+4. Provide extensions on `StyleScope` to reference theme tokens directly if they are exposed using `CompositionLocals`. For example:
+
```kotlin
val StyleScope.colors: JetsnackColors
@@ -121,14 +119,15 @@ Refer to the official documentation to complete specific development tasks:
val StyleScope.shapes: Shapes
get() = LocalJetsnackTheme.currentValue.shapes
+
+
```
### Step 3: Migrate a component to Styles API
-For each custom component (for example, `CustomButton`), complete the following
-sequence:
+For each custom component (for example, `CustomButton`), complete the following sequence:
1. **Establish a visual baseline (If an emulator is available):**
- **If you CANNOT run an Android emulator:** Skip this step entirely and proceed to Step 2.
@@ -137,8 +136,7 @@ sequence:
- **Option B (If no test exists):** Create a test using the project's existing testing framework, then run it.
- **Option C (If no framework exists):** Create a minimal screenshot test using UI Automator or Espresso, then run it.
2. **Remove individual styling parameters** : Remove styling parameters such as `backgroundColor`, `shape`, `textStyle`, and `contentPadding` from the signature - anything that `StyleScope` supports.
-3. **Add the style parameter** : Add `style: Style = Style` to the function signature. Always ensure the default value is exactly `Style` (e.g., `style:
- Style = Style`) and not a specific style default like `ChipStyleDefault` or any other value.
+3. **Add the style parameter** : Add `style: Style = Style` to the function signature. Always ensure the default value is exactly `Style` (e.g., `style: Style = Style`) and not a specific style default like `ChipStyleDefault` or any other value.
4. **Declare state tracking** : If the component is interactable, create a `MutableStyleState` using the interaction source. Update state fields (such as `isEnabled`) inside the Composable to track the state correctly.
5. **Apply styleable modifier** : Replace specific layout modifiers on the root element with `Modifier.styleable()`.
6. **Move defaults to ComponentStyles** : Move hardcoded values from the component definition to a dedicated `Style` instance in `ComponentStyles.kt`.
@@ -148,6 +146,7 @@ sequence:
Before Migration:
+
```kotlin
@Composable
@@ -172,12 +171,14 @@ fun CustomButton(
content = content,
)
}
+
```
After Migration:
+
```kotlin
// Exposed via ComponentStyles.kt
@@ -215,6 +216,7 @@ fun CustomButton(
content = content,
)
}
+
```
diff --git a/jetpack-compose/theming/styles/references/android/develop/ui/compose/designsystems/custom.md b/jetpack-compose/theming/styles/references/android/develop/ui/compose/designsystems/custom.md
index 59dbb25..ae05b5a 100644
--- a/jetpack-compose/theming/styles/references/android/develop/ui/compose/designsystems/custom.md
+++ b/jetpack-compose/theming/styles/references/android/develop/ui/compose/designsystems/custom.md
@@ -1,7 +1,4 @@
-While Material is our recommended design system and Jetpack Compose ships an
-implementation of Material, you are not forced to use it. Material is built
-entirely on public APIs, so it's possible to create your own design system in
-the same manner.
+While Material is our recommended design system and Jetpack Compose ships an implementation of Material, you are not forced to use it. Material is built entirely on public APIs, so it's possible to create your own design system in the same manner.
There are several approaches you might take:
@@ -9,21 +6,15 @@ There are several approaches you might take:
- [Replace one or more Material systems](https://developer.android.com/develop/ui/compose/designsystems/custom#replacing-systems) --- `Colors`, `Typography`, or `Shapes` --- with custom implementations while keeping the others.
- [Implement a fully custom design system](https://developer.android.com/develop/ui/compose/designsystems/custom#implementing-fully-custom) to replace `MaterialTheme`.
-You may also want to continue using Material components with a custom design
-system. It's possible to do this but there are things to keep in mind to suit
-the approach you've taken.
+You may also want to continue using Material components with a custom design system. It's possible to do this but there are things to keep in mind to suit the approach you've taken.
-To learn more about the lower-level constructs and APIs used by `MaterialTheme`
-and custom design systems, check out the [Anatomy of a theme in Compose](https://developer.android.com/develop/ui/compose/designsystems/anatomy) guide.
+To learn more about the lower-level constructs and APIs used by `MaterialTheme` and custom design systems, check out the [Anatomy of a theme in Compose](https://developer.android.com/develop/ui/compose/designsystems/anatomy) guide.
## Extend Material Theming
-Compose Material closely models
-[Material Theming](https://m3.material.io/)
-to make it straightforward and type-safe to follow the Material guidelines.
-However, it's possible to extend the color, typography, and shape sets with
-additional values. The simplest approach is to add extension properties:
+Compose Material closely models [Material Theming](https://m3.material.io/) to make it straightforward and type-safe to follow the Material guidelines. However, it's possible to extend the color, typography, and shape sets with additional values. The simplest approach is to add extension properties:
+
```kotlin
// Use with MaterialTheme.colorScheme.snackbarAction
@@ -38,26 +29,21 @@ val Typography.textFieldInput: TextStyle
// Use with MaterialTheme.shapes.card
val Shapes.card: Shape
get() = RoundedCornerShape(size = 20.dp)
+
```
-This provides consistency with `MaterialTheme` usage APIs. An example of this
-defined by Compose itself is
-[`surfaceColorAtElevation`](https://developer.android.com/reference/kotlin/androidx/compose/material3/package-summary#(androidx.compose.material3.ColorScheme).surfaceColorAtElevation(androidx.compose.ui.unit.Dp)),
-which determines the surface color that should be used depending on the
-elevation.
+This provides consistency with `MaterialTheme` usage APIs. An example of this defined by Compose itself is [`surfaceColorAtElevation`](https://developer.android.com/reference/kotlin/androidx/compose/material3/package-summary#(androidx.compose.material3.ColorScheme).surfaceColorAtElevation(androidx.compose.ui.unit.Dp)), which determines the surface color that should be used depending on the elevation.
> [!NOTE]
> **Note:** This approach is only recommended for straightforward theming value additions, or for values that are the same in different themes. If you have multiple themes, it's better to define a class with new properties instead.
-Another approach is to define an extended theme that "wraps" `MaterialTheme` and
-its values.
+Another approach is to define an extended theme that "wraps" `MaterialTheme` and its values.
-Suppose you want to add two additional colors --- `caution` and `onCaution`, a
-yellow color used for actions that are semi-dangerous --- whilst keeping the
-existing Material colors:
+Suppose you want to add two additional colors --- `caution` and `onCaution`, a yellow color used for actions that are semi-dangerous --- whilst keeping the existing Material colors:
+
```kotlin
@Immutable
@@ -96,22 +82,20 @@ object ExtendedTheme {
@Composable
get() = LocalExtendedColors.current
}
+
```
-This is similar to `MaterialTheme` usage APIs. It also supports multiple themes
-as you can nest `ExtendedTheme`s in the same way as `MaterialTheme`.
+This is similar to `MaterialTheme` usage APIs. It also supports multiple themes as you can nest `ExtendedTheme`s in the same way as `MaterialTheme`.
### Use Material components
-When extending Material Theming, existing `MaterialTheme` values are maintained
-and Material components still have reasonable defaults.
+When extending Material Theming, existing `MaterialTheme` values are maintained and Material components still have reasonable defaults.
-If you want to use extended values in components, wrap them in your own
-composable functions, directly setting the values you want to alter, and
-exposing others as parameters to the containing composable:
+If you want to use extended values in components, wrap them in your own composable functions, directly setting the values you want to alter, and exposing others as parameters to the containing composable:
+
```kotlin
@Composable
@@ -131,13 +115,14 @@ fun ExtendedButton(
content = content
)
}
+
```
-You would then replace usages of `Button` with `ExtendedButton` where
-appropriate.
+You would then replace usages of `Button` with `ExtendedButton` where appropriate.
+
```kotlin
@Composable
@@ -149,19 +134,18 @@ fun ExtendedApp() {
}
}
}
+
```
## Replace Material subsystems
-Instead of extending Material Theming, you may want to replace one or more
-systems --- `Colors`, `Typography`, or `Shapes` --- with a custom implementation,
-while maintaining the others.
+Instead of extending Material Theming, you may want to replace one or more systems --- `Colors`, `Typography`, or `Shapes` --- with a custom implementation, while maintaining the others.
-Suppose you want to replace the type and shape systems while keeping the color
-system:
+Suppose you want to replace the type and shape systems while keeping the color system:
+
```kotlin
@Immutable
@@ -222,22 +206,21 @@ object ReplacementTheme {
@Composable
get() = LocalReplacementShapes.current
}
+
```
### Use Material components
-When one or more systems of `MaterialTheme` have been replaced, using Material
-components as-is may result in unwanted Material color, type, or shape values.
+When one or more systems of `MaterialTheme` have been replaced, using Material components as-is may result in unwanted Material color, type, or shape values.
-If you want to use replacement values in components, wrap them in your own
-composable functions, directly setting the values for the relevant system, and
-exposing others as parameters to the containing composable.
+If you want to use replacement values in components, wrap them in your own composable functions, directly setting the values for the relevant system, and exposing others as parameters to the containing composable.
> [!NOTE]
> **Note:** Not all values may be exposed as parameters in Material composables, in particular with `CompositionLocal` composables (such as `LocalTextStyle`). In such cases you may need to wrap `content` lambdas in provider functions (like `ProvideTextStyle`).
+
```kotlin
@Composable
@@ -259,13 +242,14 @@ fun ReplacementButton(
}
)
}
+
```
-You would then replace usages of `Button` with `ReplacementButton` where
-appropriate.
+You would then replace usages of `Button` with `ReplacementButton` where appropriate.
+
```kotlin
@Composable
@@ -277,33 +261,28 @@ fun ReplacementApp() {
}
}
}
+
```
## Implement a fully custom design system
-You may want to replace Material Theming with a fully custom design system.
-Consider that `MaterialTheme` provides the following systems:
+You may want to replace Material Theming with a fully custom design system. Consider that `MaterialTheme` provides the following systems:
- `Colors`, `Typography`, and `Shapes`: Material Theming systems
- `TextSelectionColors`: Colors used for text selection by `Text` and `TextField`
- `Ripple` and `RippleTheme`: Material implementation of `Indication`
-If you want to continue using Material components, you must replace some of
-these systems in your custom themes or handle the systems in your
-components to avoid unwanted behavior.
+If you want to continue using Material components, you must replace some of these systems in your custom themes or handle the systems in your components to avoid unwanted behavior.
-However, design systems are not limited to the concepts Material relies on. You
-can modify existing systems and introduce entirely new ones --- with new classes
-and types --- to make other concepts compatible with themes.
+However, design systems are not limited to the concepts Material relies on. You can modify existing systems and introduce entirely new ones --- with new classes and types --- to make other concepts compatible with themes.
-In the following code, we model a custom color system that includes gradients
-(`List`), include a type system, introduce a new elevation system,
-and exclude other systems provided by `MaterialTheme`:
+In the following code, we model a custom color system that includes gradients (`List`), include a type system, introduce a new elevation system, and exclude other systems provided by `MaterialTheme`:

+
```kotlin
@Immutable
@@ -383,23 +362,20 @@ object CustomTheme {
@Composable
get() = LocalCustomElevation.current
}
+
```
### Use Material components
-When no `MaterialTheme` is present, using Material components as-is will result
-in unwanted Material color, type, and shape values and indication behavior.
+When no `MaterialTheme` is present, using Material components as-is will result in unwanted Material color, type, and shape values and indication behavior.
-If you want to use custom values in components, wrap them in your own composable
-functions, directly setting the values for the relevant system, and exposing
-others as parameters to the containing composable.
+If you want to use custom values in components, wrap them in your own composable functions, directly setting the values for the relevant system, and exposing others as parameters to the containing composable.
-We recommend that you access values you set from your custom theme.
-Alternatively, if your theme doesn't provide `Color`, `TextStyle`, `Shape`, or
-other systems, you can hardcode them.
+We recommend that you access values you set from your custom theme. Alternatively, if your theme doesn't provide `Color`, `TextStyle`, `Shape`, or other systems, you can hardcode them.
+
```kotlin
@Composable
@@ -438,6 +414,7 @@ fun CustomButton(
}
val ButtonShape = RoundedCornerShape(percent = 50)
+
```
@@ -445,11 +422,7 @@ val ButtonShape = RoundedCornerShape(percent = 50)
> [!NOTE]
> **Note:** `Button` uses `rememberRipple()` internally to provide a `Ripple` `Indication`. It's a good idea to check the source code when implementing other custom components that wrap existing components.
-If you've introduced new class types --- such as `List` to represent
-gradients --- then it may be better to implement components from scratch instead
-of wrapping them. For an example, take a look at
-[`JetsnackButton`](https://github.com/android/compose-samples/blob/main/Jetsnack/app/src/main/java/com/example/jetsnack/ui/components/Button.kt)
-from the Jetsnack sample.
+If you've introduced new class types --- such as `List` to represent gradients --- then it may be better to implement components from scratch instead of wrapping them. For an example, take a look at [`JetsnackButton`](https://github.com/android/compose-samples/blob/main/Jetsnack/app/src/main/java/com/example/jetsnack/ui/components/Button.kt) from the Jetsnack sample.
## Recommended for you
diff --git a/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/fundamentals.md b/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/fundamentals.md
index ab0d26d..901315d 100644
--- a/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/fundamentals.md
+++ b/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/fundamentals.md
@@ -6,10 +6,7 @@ There are three ways you can adopt Styles throughout your app:
## Available properties on Styles
-Styles support many of the same properties that modifiers support; however, not
-everything that is a modifier can be replicated with a Style. You still need
-modifiers for certain behaviors, like interactions, custom drawing, or stacking
-of properties.
+Styles support many of the same properties that modifiers support; however, not everything that is a modifier can be replicated with a Style. You still need modifiers for certain behaviors, like interactions, custom drawing, or stacking of properties.
| Grouping | Properties | Inherited by children |
|---|---|---|
@@ -36,6 +33,7 @@ of properties.
Components that expose a `Style` parameter allow you to set their styling:
+
```kotlin
BaseButton(
@@ -44,13 +42,14 @@ BaseButton(
) {
BaseText("Click me")
}
+
```
-Within the style lambda, you can set various properties, such as `externalPadding`
-or `background`:
+Within the style lambda, you can set various properties, such as `externalPadding` or `background`:
+
```kotlin
BaseButton(
@@ -59,19 +58,18 @@ BaseButton(
) {
BaseText("Click me")
}
+
```
-For the full list of supported properties, see [Available properties on
-Styles](https://developer.android.com/develop/ui/compose/styles/fundamentals#properties-styles).
+For the full list of supported properties, see [Available properties on Styles](https://developer.android.com/develop/ui/compose/styles/fundamentals#properties-styles).
## Apply Styles using modifiers for components with no existing parameter
-For components that lack a built-in style parameter, you can still apply styles
-with the `styleable` modifier. This approach is also useful when developing your
-own custom components.
+For components that lack a built-in style parameter, you can still apply styles with the `styleable` modifier. This approach is also useful when developing your own custom components.
+
```kotlin
Row(
@@ -79,13 +77,14 @@ Row(
) {
BaseText("Content")
}
+
```
-Similar to the `style` parameter, you can include properties like `background`,
-`contentPadding`, or `externalPadding` inside the lambda.
+Similar to the `style` parameter, you can include properties like `background`, `contentPadding`, or `externalPadding` inside the lambda.
+
```kotlin
Row(
@@ -95,6 +94,7 @@ Row(
) {
BaseText("Content")
}
+
```
@@ -102,35 +102,28 @@ Row(
> [!NOTE]
> **Note:** When using `Modifier.styleable`, the child composables won't have those properties applied to them, unless they are inherited properties. Only the container with the `styleable` modifier has those properties applied.
-Multiple chained `Modifier.styleable` modifiers are additive with non-inherited
-properties on the applied composable, behaving similarly to multiple modifiers
-defining the same properties. For inherited properties, these are overridden,
-and the last `styleable` modifier in the chain sets the values.
+Multiple chained `Modifier.styleable` modifiers are additive with non-inherited properties on the applied composable, behaving similarly to multiple modifiers defining the same properties. For inherited properties, these are overridden, and the last `styleable` modifier in the chain sets the values.
-When using `Modifier.styleable`, you may also want to create and supply a
-`StyleState` to be used with the modifier to apply state-based styling. For more
-details, see [State and animations with
-Styles](https://developer.android.com/develop/ui/compose/styles/state-animations).
+When using `Modifier.styleable`, you may also want to create and supply a `StyleState` to be used with the modifier to apply state-based styling. For more details, see [State and animations with Styles](https://developer.android.com/develop/ui/compose/styles/state-animations).
## Define a standalone Style
You can define a standalone Style for reusability purposes:
+
```kotlin
val style = Style { background(Color.Blue) }
+
```
-You can then pass that defined style into a composable's style parameter or with
-`Modifier.styleable`. When using `Modifier.styleable`, you also need to create a
-`StyleState` object. `StyleState` is covered in detail in the [State and
-animations with Styles](https://developer.android.com/develop/ui/compose/styles/state-animations) documentation.
+You can then pass that defined style into a composable's style parameter or with `Modifier.styleable`. When using `Modifier.styleable`, you also need to create a `StyleState` object. `StyleState` is covered in detail in the [State and animations with Styles](https://developer.android.com/develop/ui/compose/styles/state-animations) documentation.
-The following example shows how you can apply a Style either directly through a
-component's built-in parameters, or through a `Modifier.styleable`:
+The following example shows how you can apply a Style either directly through a component's built-in parameters, or through a `Modifier.styleable`:
+
```kotlin
val style = Style { background(Color.Blue) }
@@ -147,12 +140,14 @@ Column(
) {
BaseText("Column content")
}
+
```
You can also pass that Style into multiple components:
+
```kotlin
val style = Style { background(Color.Blue) }
@@ -176,15 +171,16 @@ Row(
) {
BaseText("Row")
}
+
```
## Add multiple Style properties
-You can add multiple Style properties by setting different properties on each
-line:
+You can add multiple Style properties by setting different properties on each line:
+
```kotlin
BaseButton(
@@ -196,6 +192,7 @@ BaseButton(
) {
BaseText("Button")
}
+
```
@@ -203,12 +200,9 @@ BaseButton(
> [!IMPORTANT]
> **Important:** Unlike modifier-based styling, properties in Styles override one another; the last property defined takes precedence.
-Properties in Styles are not additive, unlike modifier-based styling. Styles
-take the last set value in the list of properties within one style block. In the
-following example, with the background set twice, the `TealColor` is the applied
-background. For padding, `contentPaddingTop` overrides the top
-padding set by `contentPadding` and does not combine the values.
+Properties in Styles are not additive, unlike modifier-based styling. Styles take the last set value in the list of properties within one style block. In the following example, with the background set twice, the `TealColor` is the applied background. For padding, `contentPaddingTop` overrides the top padding set by `contentPadding` and does not combine the values.
+
```kotlin
BaseButton(
@@ -227,6 +221,7 @@ BaseButton(
) {
BaseText("Click me!")
}
+
```
@@ -236,9 +231,9 @@ overrides](https://developer.android.com/static/develop/ui/compose/styles/images
## Merge multiple style objects
-You can create multiple Style objects and pass them into the style parameter of
-your composable.
+You can create multiple Style objects and pass them into the style parameter of your composable.
+
```kotlin
val style1 = Style { background(TealColor) }
@@ -252,6 +247,7 @@ BaseButton(
) {
BaseText("Click me!")
}
+
```
@@ -259,12 +255,9 @@ BaseButton(
 **Figure 2.** Button with background color and `contentPaddingTop` set.
-When multiple Styles specify the same property, the last set
-property is chosen. Because properties are not additive in Styles, the last
-padding passed in overrides the `contentPaddingHorizontal` set by the initial
-`contentPadding`. Additionally, the last background color overrides the
-background color set by the initial style passed in.
+When multiple Styles specify the same property, the last set property is chosen. Because properties are not additive in Styles, the last padding passed in overrides the `contentPaddingHorizontal` set by the initial `contentPadding`. Additionally, the last background color overrides the background color set by the initial style passed in.
+
```kotlin
val style1 = Style {
@@ -285,12 +278,12 @@ BaseButton(
) {
BaseText("Click me!")
}
+
```
-In this case, the styling applied has a light gray background and `32.dp` padding,
-except for the left and right padding, which has a value of `8.dp`.
+In this case, the styling applied has a light gray background and `32.dp` padding, except for the left and right padding, which has a value of `8.dp`.
 **Figure 3.** Button with `contentPadding` that's overridden by different Styles.
@@ -299,9 +292,7 @@ Styles](https://developer.android.com/static/develop/ui/compose/styles/images/bu
> [!NOTE]
> **Note:** While the Style APIs are experimental, you need to opt-in to enable Style inheritance by setting the flag `ComposeFoundationFlags.isInheritedTextStyleEnabled = true`.
-Certain style properties, such as `contentColor` and text style-related
-properties, propagate to the child composables. A style set on a child
-composable overrides the inherited parent styling for that specific child.
+Certain style properties, such as `contentColor` and text style-related properties, propagate to the child composables. A style set on a child composable overrides the inherited parent styling for that specific child.
 **Figure 4.** Style propagation with `Style`, `styleable`, and direct parameters.
@@ -317,9 +308,9 @@ parameters](https://developer.android.com/static/develop/ui/compose/styles/image
### Parent styling
-You can set text properties (such as `contentColor`) from the parent composable,
-and they propagate to all child `Text` composables.
+You can set text properties (such as `contentColor`) from the parent composable, and they propagate to all child `Text` composables.
+
```kotlin
val styleState = remember { MutableStyleState(null) }
@@ -336,6 +327,7 @@ Column(
BaseText("certain properties")
BaseText("from their parents")
}
+
```
@@ -345,10 +337,9 @@ inheritance](https://developer.android.com/static/develop/ui/compose/styles/imag
### Child override of properties
-You can also set styling on a specific `Text` composable. If the parent composable
-has styling set, the styling set on the child composable overrides the
-parent composable's styling.
+You can also set styling on a specific `Text` composable. If the parent composable has styling set, the styling set on the child composable overrides the parent composable's styling.
+
```kotlin
val styleState = remember { MutableStyleState(null) }
@@ -367,6 +358,7 @@ Column(
BaseText("override properties")
BaseText("set by their parents")
}
+
```
@@ -376,39 +368,40 @@ properties](https://developer.android.com/static/develop/ui/compose/styles/image
## Implement custom Style properties
-You can create custom properties that map to existing Style definitions by using
-extension functions on the `StyleScope`, as shown in the following example:
+You can create custom properties that map to existing Style definitions by using extension functions on the `StyleScope`, as shown in the following example:
+
```kotlin
fun StyleScope.outlinedBackground(color: Color) {
border(1.dp, color)
background(color)
}
+
```
Apply this new property within a Style definition:
+
```kotlin
val customExtensionStyle = Style {
outlinedBackground(Color.Blue)
}
+
```
-Creating new styleable properties is unsupported. If your use case
-requires such support, submit a [feature request](https://issuetracker.google.com/issues/new?component=612128).
+Creating new styleable properties is unsupported. If your use case requires such support, submit a [feature request](https://issuetracker.google.com/issues/new?component=612128).
## Read `CompositionLocal` values
-It's a common pattern to store design system tokens within a `CompositionLocal`,
-to access the variables without needing to pass them as parameters. Styles
-can access `CompositionLocal`s to retrieve system-wide values within a style:
+It's a common pattern to store design system tokens within a `CompositionLocal`, to access the variables without needing to pass them as parameters. Styles can access `CompositionLocal`s to retrieve system-wide values within a style:
+
```kotlin
val buttonStyle = Style {
@@ -416,6 +409,7 @@ val buttonStyle = Style {
shape(RoundedCornerShape(50))
background(Brush.verticalGradient(LocalCustomColors.currentValue.background))
}
+
```
\ No newline at end of file
diff --git a/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/state-animations.md b/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/state-animations.md
index 01683bd..8c387a6 100644
--- a/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/state-animations.md
+++ b/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/state-animations.md
@@ -1,15 +1,8 @@
-The Styles API offers a declarative and streamlined approach to managing UI
-changes during interaction states like `hovered`, `focused`, and `pressed`. With
-this API, you can significantly decrease the boilerplate code typically required
-when using modifiers.
+The Styles API offers a declarative and streamlined approach to managing UI changes during interaction states like `hovered`, `focused`, and `pressed`. With this API, you can significantly decrease the boilerplate code typically required when using modifiers.
-To facilitate reactive styling, `StyleState` acts as a stable, read-only
-interface that tracks the active state of an element (such as its enabled,
-pressed, or focused status). Within a `StyleScope`, you can access this through
-the `state` property to implement conditional logic directly in your Style
-definitions.
+To facilitate reactive styling, `StyleState` acts as a stable, read-only interface that tracks the active state of an element (such as its enabled, pressed, or focused status). Within a `StyleScope`, you can access this through the `state` property to implement conditional logic directly in your Style definitions.
## State-based interaction: Hovered, focused, pressed, selected, enabled, toggled
@@ -21,15 +14,13 @@ Styles come with built-in support for common interactions:
- Enabled
- Toggled
-It's also possible to support custom states. See the [Custom State Styling with
-StyleState](https://developer.android.com/develop/ui/compose/styles/state-animations#custom-state) section for more information.
+It's also possible to support custom states. See the [Custom State Styling with StyleState](https://developer.android.com/develop/ui/compose/styles/state-animations#custom-state) section for more information.
### Handle interaction states with Style parameters
-The following example demonstrates modifying the `background` and `borderColor`
-in response to interaction states, specifically switching to purple when hovered
-and blue when focused:
+The following example demonstrates modifying the `background` and `borderColor` in response to interaction states, specifically switching to purple when hovered and blue when focused:
+
```kotlin
@Preview
@@ -56,16 +47,17 @@ private fun OpenButton() {
}
)
}
+
+
```
**Figure 1.** Changing background color based on hovered and focused states.
-You can also create nested state definitions. For example, you can define a
-specific style for when a button is being both pressed and hovered
-simultaneously:
+You can also create nested state definitions. For example, you can define a specific style for when a button is being both pressed and hovered simultaneously:
+
```kotlin
@Composable
@@ -99,6 +91,7 @@ private fun OpenButton_CombinedStates() {
}
)
}
+
```
@@ -107,18 +100,15 @@ private fun OpenButton_CombinedStates() {
### Custom composables with Modifier.styleable
-When creating your own `styleable` components, you must connect an
-`interactionSource` to a `styleState`. Then, pass this state into
-`Modifier.styleable` to utilize it.
+When creating your own `styleable` components, you must connect an `interactionSource` to a `styleState`. Then, pass this state into `Modifier.styleable` to utilize it.
-Consider a scenario where your design system includes a `GradientButton`. You
-may want to create a `LoginButton` that inherits from `GradientButton`, but
-alters its colors during interactions, like being pressed.
+Consider a scenario where your design system includes a `GradientButton`. You may want to create a `LoginButton` that inherits from `GradientButton`, but alters its colors during interactions, like being pressed.
- To enable `interactionSource` style updates, include an `interactionSource` as a parameter within your composable. Use the provided parameter or, if one is not supplied, initialize a new `MutableInteractionSource`.
- Initialize the `styleState` by providing the `interactionSource`. Make sure the `styleState`'s enabled status reflects the value of the provided enabled parameter.
- Assign the `interactionSource` to the `focusable` and `clickable` modifiers. Finally, apply the `styleState` to the modifier's `styleable` parameter.
+
```kotlin
@Composable
@@ -147,13 +137,14 @@ private fun GradientButton(
content = content,
)
}
+
```
-You can now use the `interactionSource` state to drive style modifications with
-the pressed, focused, and hovered options inside the style block:
+You can now use the `interactionSource` state to drive style modifications with the pressed, focused, and hovered options inside the style block:
+
```kotlin
@Preview
@@ -174,6 +165,7 @@ fun LoginButton() {
BaseText("Login")
}
}
+
```
@@ -182,12 +174,9 @@ fun LoginButton() {
## Animate style changes
-Styles state changes come with built-in animation support. You can wrap the new
-property within any state change block with `animate` to automatically add
-animations between different states. This is similar to the `animate*AsState`
-APIs. The following example animates the `borderColor` from black to blue when
-the state changes to focused:
+Styles state changes come with built-in animation support. You can wrap the new property within any state change block with `animate` to automatically add animations between different states. This is similar to the `animate*AsState` APIs. The following example animates the `borderColor` from black to blue when the state changes to focused:
+
```kotlin
val animatingStyle = Style {
@@ -222,16 +211,16 @@ private fun AnimatingStyleChanges() {
}
}
+
```
**Figure 4.** Animating color changes on press.
-The `animate` API accepts an `animationSpec` to change the duration or shape of
-the animation curve. The following example animates the size of the box with a
-`spring` spec:
+The `animate` API accepts an `animationSpec` to change the duration or shape of the animation curve. The following example animates the size of the box with a `spring` spec:
+
```kotlin
val animatingStyleSpec = Style {
@@ -267,6 +256,7 @@ fun AnimatingStyleChangesSpec() {
)
.styleable(styleState, animatingStyleSpec))
}
+
```
@@ -275,11 +265,7 @@ fun AnimatingStyleChangesSpec() {
## Custom state styling with StyleState
-Depending on your composable use case, you may have different styles that are
-backed by custom states. For example, if you have a media app, you may want to
-have different styling for the buttons in your `MediaPlayer` composable
-depending on the playback state of the player. Follow these steps to create and
-use your own custom state:
+Depending on your composable use case, you may have different styles that are backed by custom states. For example, if you have a media app, you may want to have different styling for the buttons in your `MediaPlayer` composable depending on the playback state of the player. Follow these steps to create and use your own custom state:
1. Define custom key
2. Create `StyleState` extension
@@ -287,11 +273,9 @@ use your own custom state:
### Define custom key
-To create a custom state-based style, first create a
-[`StyleStateKey`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/style/StyleStateKey) and pass in the default state value. When the
-app launches, the media player is in the `Stopped` state, so it's initialized in
-this way:
+To create a custom state-based style, first create a [`StyleStateKey`](https://developer.android.com/reference/kotlin/androidx/compose/foundation/style/StyleStateKey) and pass in the default state value. When the app launches, the media player is in the `Stopped` state, so it's initialized in this way:
+
```kotlin
enum class PlayerState {
@@ -301,16 +285,16 @@ enum class PlayerState {
}
val playerStateKey = StyleStateKey(PlayerState.Stopped)
+
```
### Create StyleState extension functions
-Define an extension function on `StyleState` to query the current `playState`.
-Then, create extension functions on `StyleScope` with your custom states passing
-in the `playStateKey`, a lambda with the specific state, and the style.
+Define an extension function on `StyleState` to query the current `playState`. Then, create extension functions on `StyleScope` with your custom states passing in the `playStateKey`, a lambda with the specific state, and the style.
+
```kotlin
// Extension Function on MutableStyleState to query and set the current playState
@@ -324,16 +308,16 @@ fun StyleScope.playerPlaying(block: () -> Unit) {
fun StyleScope.playerPaused(block: () -> Unit) {
state(playerStateKey, block, { key, state -> state[key] == PlayerState.Paused })
}
+
```
### Link to custom state
-Define the `styleState` in your composable and set the `styleState.playState`
-equal to incoming state. Pass `styleState` into the `styleable` function on the
-modifier.
+Define the `styleState` in your composable and set the `styleState.playState` equal to incoming state. Pass `styleState` into the `styleable` function on the modifier.
+
```kotlin
@Composable
@@ -352,13 +336,14 @@ fun MediaPlayer(
///..
}
}
+
```
-Within the `style` lambda, you can apply state-based styling for custom states,
-using the previously defined extension functions.
+Within the `style` lambda, you can apply state-based styling for custom states, using the previously defined extension functions.
+
```kotlin
@Composable
@@ -385,12 +370,14 @@ fun StyleStateKeySample() {
style = style,
state = PlayerState.Stopped)
}
+
```
The following code is the full snippet for this example:
+
```kotlin
enum class PlayerState {
@@ -456,6 +443,7 @@ fun StyleStateKeySample() {
style = style,
state = PlayerState.Stopped)
}
+
```
\ No newline at end of file
diff --git a/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/styles-vs-modifiers.md b/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/styles-vs-modifiers.md
index cd9bc50..e6a756b 100644
--- a/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/styles-vs-modifiers.md
+++ b/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/styles-vs-modifiers.md
@@ -1,7 +1,4 @@
-Styles differ from modifiers by design. Styles don't replace modifiers; instead,
-the two systems coexist with different goals. Internally, a Style is a modifier.
-You can do everything Styles can do with modifiers, but not all functionality in
-modifiers is available in Styles.
+Styles differ from modifiers by design. Styles don't replace modifiers; instead, the two systems coexist with different goals. Internally, a Style is a modifier. You can do everything Styles can do with modifiers, but not all functionality in modifiers is available in Styles.
**Important:**
- **Choose Styles if:** You need to override a default of an existing component, perform high-performance animations, or define a theme-wide set of properties for a component.
@@ -19,8 +16,7 @@ The following is a comparison between Styles versus modifiers:
## Limitations of modifiers
-Modifiers have many benefits in the current Compose landscape. However, Styles
-address some limitations of modifiers, which the following list describes:
+Modifiers have many benefits in the current Compose landscape. However, Styles address some limitations of modifiers, which the following list describes:
- Modifiers are typically created in the Composition phase. Updates can force a full rerun of Composition, Layout, and Draw, even for small visual changes like color, unless you create lambda-based modifiers.
- Conditional modifiers require disruptive if-else logic within fluent chains. Animating them requires manual state boilerplate and lacks a high-performance "auto-animate" mechanism.
@@ -29,18 +25,15 @@ address some limitations of modifiers, which the following list describes:
## Limitations of Styles
-While Styles can fill in some of the gaps that modifiers have, they also have
-some limitations, which show how they cannot entirely replace modifiers:
+While Styles can fill in some of the gaps that modifiers have, they also have some limitations, which show how they cannot entirely replace modifiers:
- Styles are specialized Modifiers. While a modifier can do anything a Style does, the reverse is not true. Consequently, Styles can supplement, but cannot replace, modifiers.
- Styles are limited to visual configuration (backgrounds, padding, borders). They cannot handle behaviors like click logic, gesture detection, or accessibility semantics.
-- Resolving a Style into its final state is *more expensive than applying a
- single modifier*. The system must generate a data structure containing all possible property values, and the lookup of inherited properties further complicates this.
+- Resolving a Style into its final state is *more expensive than applying a single modifier*. The system must generate a data structure containing all possible property values, and the lookup of inherited properties further complicates this.
## When to use Styles over modifiers
-While the choice to use Styles is largely dependent on your app and use cases,
-the following guidance helps determine when to prefer a style over a modifier:
+While the choice to use Styles is largely dependent on your app and use cases, the following guidance helps determine when to prefer a style over a modifier:
- **To achieve theme-wide consistency:** Styles are designed to be "lifted" into a global theme. Instead of passing repetitive Modifiers to every component, you can define a single Style in your theme to create a unified look across the entire app.
- **When performing frequent animations:** Styles evaluate during the Layout and Draw phases, allowing properties like color or scale to animate while bypassing the Composition phase entirely. This significantly reduces performance overhead. Use a Style instead of a modifier when doing visual property animations.
diff --git a/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/theming.md b/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/theming.md
index c8a373b..e80dfb9 100644
--- a/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/theming.md
+++ b/jetpack-compose/theming/styles/references/android/develop/ui/compose/styles/theming.md
@@ -1,8 +1,7 @@
> [!NOTE]
> **Note:** Styles are `@Experimental` and likely to change in upcoming releases, with Material support for Styles added in future releases. If you have any feedback, [file Styles issues](https://issuetracker.google.com/issues/new?component=612128).
-There are several ways you can build out your apps using Styles. What you choose
-depends on where your app sits in relation to its adoption of Material Design:
+There are several ways you can build out your apps using Styles. What you choose depends on where your app sits in relation to its adoption of Material Design:
1. Fully custom design system, not using Material Design
- **Recommendation**: Define component styles that consume values from the theme, and expose style parameters on design system components.
@@ -11,15 +10,9 @@ depends on where your app sits in relation to its adoption of Material Design:
## The Style layer
-In the traditional Compose model, customization often relies heavily on
-overriding global tokens (colors and typography) provided by `MaterialTheme`, or
-wrapping and overriding properties of a design system composable where possible.
-Sometimes, there are properties within the Material layer that are not exposed
-through the subsystems or parameters, but are hardcoded defaults on the
-component itself.
+In the traditional Compose model, customization often relies heavily on overriding global tokens (colors and typography) provided by `MaterialTheme`, or wrapping and overriding properties of a design system composable where possible. Sometimes, there are properties within the Material layer that are not exposed through the subsystems or parameters, but are hardcoded defaults on the component itself.
-With the Styles API, there's a new layer of abstraction that's a bridge between
-subsystems and components: **Styles**.
+With the Styles API, there's a new layer of abstraction that's a bridge between subsystems and components: **Styles**.
| Layer | Responsibility | Example |
|---|---|---|
@@ -32,11 +25,9 @@ subsystems and components: **Styles**.
### Atomic versus monolithic Styles
-With the Styles API, you can break down a Style into separate atomic styles.
-Instead of defining complex, component-specific styles like `baseButtonStyle`,
-you can also create small, single-purpose utility styles. These act as your
-"atoms".
+With the Styles API, you can break down a Style into separate atomic styles. Instead of defining complex, component-specific styles like `baseButtonStyle`, you can also create small, single-purpose utility styles. These act as your "atoms".
+
```kotlin
// Define single-purpose "atomic" styles
@@ -69,19 +60,18 @@ val interactiveShadowAtomic = Style {
}
}
}
+
+
```
#### Composition using "then"
-One of the powerful features of the new Styles API is the `then` operator, which
-lets you merge multiple `Style` objects. This lets you build a component using
-atomic utility classes.
+One of the powerful features of the new Styles API is the `then` operator, which lets you merge multiple `Style` objects. This lets you build a component using atomic utility classes.
**Traditional (non-atomic)**:
-
```kotlin
// One large monolithic style
val buttonStyle = Style {
@@ -89,49 +79,39 @@ val buttonStyle = Style {
shape(RoundedCornerShape(8.dp))
background(Color.Blue)
}
+
```
**Atomic refactor**:
-
```kotlin
// Combine atoms to create the final appearance
val buttonStyle = paddingAtomic then roundedCornerShapeAtomic then primaryBackgroundAtomic then interactiveShadowAtomic
+
```
## Adopt Styles in your design system
-Consider the following options when adopting Styles within your design system,
-depending on where in the spectrum your design system lies.
+Consider the following options when adopting Styles within your design system, depending on where in the spectrum your design system lies.
### Custom design system with Styles
-***Consider when**: You've been handed an extensive brand guide that is not
-based on Material Design, and you are not planning to use Material Design*.
+***Consider when**: You've been handed an extensive brand guide that is not based on Material Design, and you are not planning to use Material Design*.
-***Strategy**: Implement a fully custom design system, and expose styles as part
-of the theme*.
+***Strategy**: Implement a fully custom design system, and expose styles as part of the theme*.
-This option is the custom path if you don't use Material as your main design
-system language. You bypass `MaterialTheme` entirely for visual definitions and
-have created your [own custom theme already](https://developer.android.com/develop/ui/compose/designsystems/custom#implementing-fully-custom). You build a `CompanyTheme` that
-acts as a container for your Styles.
+This option is the custom path if you don't use Material as your main design system language. You bypass `MaterialTheme` entirely for visual definitions and have created your [own custom theme already](https://developer.android.com/develop/ui/compose/designsystems/custom#implementing-fully-custom). You build a `CompanyTheme` that acts as a container for your Styles.
- **How it works** : Create a `CompanyTheme` object that holds `Style` objects for every component in your system. Your components (either wrappers around Material logic or custom `Box` or `Layout` implementations) consume these styles directly, and expose a `Style` parameter for consumers of your design system.
- **The Style layer**: Styles are the primary definition of your design system. Tokens are named variables fed into these styles. This allows for deep customization, such as defining unique animations for state changes (for example, animating scale and color on press).
-If you are building out your own [custom theme](https://developer.android.com/develop/ui/compose/designsystems/custom) without using Material, and
-want to adopt styles, add your list of styles to your Theme. This lets you
-access your base styles from anywhere in your project.
-
-1. Create a `Styles` class that stores the various styles in your application
- and create the defaults. For example, in the Jetsnack app - the class is
- named `JetsnackStyles`:
+If you are building out your own [custom theme](https://developer.android.com/develop/ui/compose/designsystems/custom) without using Material, and want to adopt styles, add your list of styles to your Theme. This lets you access your base styles from anywhere in your project.
+1. Create a `Styles` class that stores the various styles in your application and create the defaults. For example, in the Jetsnack app - the class is named `JetsnackStyles`:
```kotlin
object JetsnackStyles{
@@ -154,13 +134,12 @@ access your base styles from anywhere in your project.
contentColor(colors.textPrimary)
}
}
+
```
-2. Provide `Styles` as part of your overall theme, and expose helper extension
- functions on `StyleScope` to access the subsystems:
-
+2. Provide `Styles` as part of your overall theme, and expose helper extension functions on `StyleScope` to access the subsystems:
```kotlin
@Immutable
@@ -215,13 +194,13 @@ access your base styles from anywhere in your project.
)
}
}
+
```
3. Access `JetsnackStyles` within your composable:
-
```kotlin
@Composable
fun CustomButton(modifier: Modifier,
@@ -245,13 +224,9 @@ access your base styles from anywhere in your project.
Text(text)
}
}
+
```
-Beyond global theme adoption, there are alternative strategies for incorporating
-`Styles` into your apps. You can leverage `Styles` inline for specific call
-sites or use static definitions when full theming capabilities are unnecessary.
-`Styles` shouldn't be swapped conditionally unless the whole style is
-fundamentally different. You should prefer accessing dynamic tokens inside a
-visual definition rather than switching between distinct style objects.
\ No newline at end of file
+Beyond global theme adoption, there are alternative strategies for incorporating `Styles` into your apps. You can leverage `Styles` inline for specific call sites or use static definitions when full theming capabilities are unnecessary. `Styles` shouldn't be swapped conditionally unless the whole style is fundamentally different. You should prefer accessing dynamic tokens inside a visual definition rather than switching between distinct style objects.
\ No newline at end of file
diff --git a/media/media3-cast-integration/SKILL.md b/media/media3-cast-integration/SKILL.md
new file mode 100644
index 0000000..e6fb809
--- /dev/null
+++ b/media/media3-cast-integration/SKILL.md
@@ -0,0 +1,224 @@
+---
+name: media3-cast-integration
+description: Implements Google Cast support in Android apps using Jetpack Media3.
+ Handles adding build dependencies, updating manifest, configuring OptionsProvider,
+ and managing CastPlayer or RemoteCastPlayer for playback in both Compose and View-based
+ UIs. Use when adding Cast functionality or migrating from legacy Cast SDK to Media3
+ Cast.
+license: Complete terms in LICENSE.txt
+metadata:
+ author: Google LLC
+ last-updated: '2026-08-06'
+ keywords:
+ - Android
+ - Media3
+ - Cast
+ - Integration
+ - Migration
+ - ExoPlayer
+ - MediaSession
+ - Jetpack Media3
+---
+
+## Prerequisites
+
+- Jetpack Media3 version must be `>= 1.9.0`. Cast isn't available in lower versions.
+
+## Glossary
+
+- **`CastPlayer`** : Media3 `Player` that controls playback on both local and remote Cast devices.
+- **`RemoteCastPlayer`** : Media3 `Player` that communicates with a Cast receiver, only used for remote playback.
+- **Google Cast SDK**: Legacy casting SDK in maintenance mode, superseded by Jetpack Media3.
+- **`OptionsProvider`** : Interface providing configuration options to initialize GMS `CastContext`.
+
+## Common guidelines
+
+- Legacy [Google Cast SDK](https://developers.google.com/cast) is in maintenance mode.
+- For new Cast setups:
+ - You must use [Jetpack Media3 Cast](references/android/media/media3/cast/index.md).
+ - You mustn't use legacy Cast SDK unless explicitly requested.
+
+## Step 1: Set up dependencies
+
+To complete this step, you **MUST** ensure the following:
+
+- In the app-level build file, declare the `media3-cast` dependency version 1.9.0 or higher.
+
+ implementation("androidx.media3:media3-cast:1.10.1")
+
+- Ensure required Media3 dependencies are present:
+
+ - `androidx.media3:media3-exoplayer`
+ - `androidx.media3:media3-session`
+ - `androidx.media3:media3-ui-compose`
+- If the application uses legacy Views, add `media3-ui`.
+
+- Enforce the same versions across all Media3 dependencies.
+
+- Use configurations in "Add build dependencies" section of [Getting started with CastPlayer](references/android/media/media3/cast/create-castplayer.md) as the source of truth.
+
+- **For apps without an existing Cast integration:**
+
+ - Verify legacy Cast SDK (`libs.play.services.cast.framework`) is absent.
+- **If Migrating from Legacy Cast SDK:**
+
+ - Add Media3 Cast dependencies first.
+ - Keep existing legacy dependencies untouched at this stage to prevent compilation errors.
+
+## Step 2: Update the manifest
+
+To complete this step, you **MUST** ensure the following:
+
+- Inside the manifest's `` tag, declare the Cast options provider.
+- Use `DefaultCastOptionsProvider` by default. See the "OptionsProvider" section in [Getting started with CastPlayer](references/android/media/media3/cast/create-castplayer.md).
+- Declare a custom `OptionsProvider` only if explicitly requested. See [Customize CastOptions](references/android/media/media3/cast/customize-castoptions.md).
+- Ensure `INTERNET` permission is present. Don't add any unnecessary permissions.
+- **If Migrating from Legacy Cast SDK:**
+ - Don't delete existing custom options provider files or manifest entries.
+
+## Step 3: Implement the player and service
+
+### Architecture baseline
+
+Before integrating Media3 Cast, an existing app follows one of two setups:
+
+- **Local-only playback:** Uses Media3 `ExoPlayer` only to support local playback.
+- **Legacy Cast setup:** Uses `ExoPlayer` for local playback, alongside a `Player` wrapper over the legacy `RemoteMediaClient` for remote playback. The UI interfaces with a `MediaSession` interacting with a `ForwardingPlayer`, which finally routes controls to either local or remote playback.
+
+To complete this step, you **MUST** ensure the following:
+
+- Inside the application's `MediaSessionService` (or `MediaLibraryService`) `onCreate()` method, initialize `ExoPlayer` and `CastPlayer`.
+- Use `CastPlayer` by default unless `RemoteCastPlayer` is explicitly requested. See the "Build a CastPlayer" section in [Getting started with CastPlayer](references/android/media/media3/cast/create-castplayer.md).
+- For `CastPlayer`, pass the instance directly to `MediaSession.Builder`.
+- Replace all legacy forwarding player wrappers.
+- Don't delete legacy class files yet to prevent compilation errors during migration.
+
+### Advanced: `RemoteCastPlayer`
+
+- Use `RemoteCastPlayer` only if explicitly requested by user.
+- Initialize `MediaSession` with `localPlayer` and set a `SessionAvailabilityListener` on `RemoteCastPlayer` to transfer playback state on Cast session availability changes:
+
+ class PlaybackService : MediaSessionService() {
+ private var mediaSession: MediaSession? = null
+ private lateinit var localPlayer: ExoPlayer
+ private lateinit var remotePlayer: RemoteCastPlayer
+
+ override fun onCreate() {
+ super.onCreate()
+
+ localPlayer = ExoPlayer.Builder(this).build()
+ remotePlayer = RemoteCastPlayer.Builder(this).build()
+ mediaSession = MediaSession.Builder(this, localPlayer).build()
+
+ remotePlayer.setSessionAvailabilityListener(
+ object : SessionAvailabilityListener {
+ override fun onCastSessionAvailable() {
+ transferPlaybackState(localPlayer, remotePlayer)
+ }
+
+ override fun onCastSessionUnavailable() {
+ transferPlaybackState(remotePlayer, localPlayer)
+ }
+ }
+ )
+ }
+
+ private fun transferPlaybackState(previousPlayer: Player, newPlayer: Player) {
+ if (previousPlayer.mediaItemCount > 0) {
+ val transferStateBuilder = PlayerTransferState.builderFromPlayer(previousPlayer)
+ if (previousPlayer.playbackState == Player.STATE_ENDED ||
+ previousPlayer.currentPosition == C.TIME_END_OF_SOURCE) {
+ transferStateBuilder.setCurrentMediaItemIndex(0)
+ transferStateBuilder.setCurrentPosition(0)
+ }
+ transferStateBuilder.build().setToPlayer(newPlayer)
+ }
+
+ previousPlayer.stop()
+ previousPlayer.clearMediaItems()
+ newPlayer.prepare()
+ mediaSession?.setPlayer(newPlayer)
+ }
+ }
+
+## Step 4: Set up the UI
+
+### Compose-based UI
+
+To complete this step, you **MUST** ensure the following:
+
+- See the "Add a MediaRouteButton Composable to the Player" section in [Getting started with CastPlayer](references/android/media/media3/cast/create-castplayer.md) for Compose integration guidelines.
+- Use the [`MediaRouteButton` composable](https://developer.android.com/reference/kotlin/androidx/media3/cast/MediaRouteButton.composable) from `androidx.media3.cast` package.
+- Don't use `AndroidView` in the Compose UI hierarchy.
+- Place `MediaRouteButton` in an area next to playback controls. Don't hide it behind system UI.
+- Don't use `PlayerSurface` for custom player UI. Use the Material3 [`Player` composable](https://developer.android.com/reference/kotlin/androidx/media3/ui/compose/material3/Player.composable).
+- Force recomposition on playback location shifts to ensure UI sync. Use key constraints on `DeviceInfo` changes:
+
+ @OptIn(UnstableApi::class)
+ @Composable
+ fun MainScreen() {
+ val player = rememberMediaController()
+ val deviceInfo = rememberDeviceInfo(player)
+ player?.let { activePlayer -> key(deviceInfo) { PlayerScreen(player = activePlayer) } }
+ }
+
+ @Composable
+ private fun rememberMediaController(): Player? {
+ // Logic to connect MediaController to MediaSession and release it
+ }
+
+ @Composable
+ private fun rememberDeviceInfo(player: Player?): DeviceInfo? {
+ var deviceInfo by remember(player) { mutableStateOf(player?.deviceInfo) }
+ DisposableEffect(player) {
+ val activePlayer = player ?: return@DisposableEffect onDispose {}
+ deviceInfo = activePlayer.deviceInfo
+ val listener = object : Player.Listener {
+ override fun onDeviceInfoChanged(info: DeviceInfo) {
+ deviceInfo = info
+ }
+ }
+ activePlayer.addListener(listener)
+ onDispose { activePlayer.removeListener(listener) }
+ }
+ return deviceInfo
+ }
+
+### View-based UI
+
+To complete this step, you **MUST** ensure the following:
+
+- For View-based UI setups, see the "Add UI elements" section in [Getting started with CastPlayer](references/android/media/media3/cast/create-castplayer.md).
+- Casting Activities must extend `AppCompatActivity` or `FragmentActivity` and use a `Theme.AppCompat` descendant.
+- Ensure the `AppCompat` theme has a visible `ActionBar` if adding `MediaRouteButton` to the options menu.
+- Replace all instances and imports of `CastButtonFactory` with `MediaRouteButtonFactory`.
+- Rebind `PlayerView.player` references upon `onDeviceInfoChanged` events to prevent black screens or UI freezes:
+
+ private val playerListener: Player.Listener =
+ object : Player.Listener {
+ override fun onDeviceInfoChanged(deviceInfo: DeviceInfo) {
+ // Resetting to null bypasses PlayerView.setPlayer()'s instance equality check
+ // (this.player == player), forcing it to re-bind the video surface to the controller.
+ playerView.player = null
+ playerView.player = controller
+ }
+ }
+
+- **Migration to Compose:**
+
+ - Don't use `AndroidView` to wrap the legacy `PlayerView`.
+ - Implement Material3 [`Player` composable](https://developer.android.com/reference/kotlin/androidx/media3/ui/compose/material3/Player.composable) and [`MediaRouteButton` composable](https://developer.android.com/reference/kotlin/androidx/media3/cast/MediaRouteButton.composable) as per [Getting started with CastPlayer](references/android/media/media3/cast/create-castplayer.md).
+ - Remove legacy XML layout declarations, menu files, and View component references.
+
+## Step 5: Clean up legacy Cast SDK code
+
+> [!WARNING]
+> **Warning:** Don't perform cleanup directly. Remove legacy files and dependencies only when explicitly requested by the user.
+
+To complete this step, you **MUST** ensure the following:
+
+- Remove legacy GMS Cast SDK (`libs.play.services.cast.framework`) and MediaRouter (`libs.androidx.mediarouter`) dependencies.
+- Delete custom `OptionsProvider` classes and manifest entries if `DefaultCastOptionsProvider` is adopted.
+- Remove legacy `MediaTransferReceiver` manifest declarations if present.
+- Remove all references to legacy Cast SDK components such as legacy helper wrappers, forwarding players, and `RemoteMediaClient` interfaces.
+- Delete legacy View XML layouts, menu files, and references to `PlayerView` if the migration to Compose is complete.
diff --git a/media/media3-cast-integration/references/android/media/media3/cast/create-castplayer.md b/media/media3-cast-integration/references/android/media/media3/cast/create-castplayer.md
new file mode 100644
index 0000000..9edd7bb
--- /dev/null
+++ b/media/media3-cast-integration/references/android/media/media3/cast/create-castplayer.md
@@ -0,0 +1,367 @@
+The [`CastPlayer`](https://developer.android.com/reference/androidx/media3/cast/CastPlayer) is a Jetpack Media3 [Player](https://developer.android.com/reference/kotlin/androidx/media3/common/Player) implementation that supports both local playback and casting to a remote Cast-enabled device. [`CastPlayer`](https://developer.android.com/reference/androidx/media3/cast/CastPlayer) simplifies adding cast functionality to your app and provides rich features to seamlessly switch between local and remote playback. This guide shows you how to integrate [`CastPlayer`](https://developer.android.com/reference/androidx/media3/cast/CastPlayer) into your media app.
+
+To integrate Cast with other platforms, see the [Cast SDK](https://developers.google.com/cast/docs/developers).
+
+## Get a Cast-enabled device
+
+To test `CastPlayer`, you need a [Cast-enabled device](https://store.google.com/gb/category/connected_home?hl=en-GB). Choices include Android TV, Chromecast, smart speakers, and smart displays. Verify that your device is set up and connected to the same Wi-Fi network as your development mobile for discovery.
+
+## Add build dependencies
+
+To start using `CastPlayer`, add the AndroidX Media3 and `CastPlayer` dependencies to the `build.gradle` file of your app module.
+
+### Kotlin
+
+ implementation("androidx.media3:media3-exoplayer:1.10.1")
+ implementation("androidx.media3:media3-ui:1.10.1")
+ implementation("androidx.media3:media3-session:1.10.1")
+ implementation("androidx.media3:media3-cast:1.10.1")
+
+### Groovy
+
+ implementation "androidx.media3:media3-exoplayer:1.10.1"
+ implementation "androidx.media3:media3-ui:1.10.1"
+ implementation "androidx.media3:media3-session:1.10.1"
+ implementation "androidx.media3:media3-cast:1.10.1"
+
+## Configure your CastPlayer
+
+To configure the [`CastPlayer`](https://developer.android.com/reference/androidx/media3/cast/CastPlayer), update your `AndroidManifest.xml` file with an options provider.
+
+### Options provider
+
+The [`CastPlayer`](https://developer.android.com/reference/androidx/media3/cast/CastPlayer) requires an options provider to configure its behavior. For a basic setup, you can use the [`DefaultCastOptionsProvider`](https://developer.android.com/reference/androidx/media3/cast/DefaultCastOptionsProvider) by adding it to your `AndroidManifest.xml` file. This uses default settings, including the default receiver application.
+
+
+ ...
+
+ ...
+
+
+To customize the configuration, implement your own custom `OptionsProvider`. See the [CastOptions](https://developer.android.com/media/media3/cast/customize-castoptions) guide to learn how.
+
+### Add a receiver for media transfers
+
+Adding a `MediaTransferReceiver` to your manifest enables the System UI to discover Cast-enabled devices on the network and reroute media without opening the app activity. For example, a user can change the device playing your app's media from the [media notification](https://developer.android.com/media/implement/surfaces/mobile).
+
+
+ ...
+
+ ...
+
+
+## Build a CastPlayer
+
+For remote playback with Cast, your app should be able to manage playback even when the user isn't interacting with an Activity from your app, such as through the system media notification. For this reason, you should create your `ExoPlayer` (for local playback) and `CastPlayer` (for remote playback) instances in a service, such as [MediaSessionService](https://developer.android.com/media/media3/session/background-playback#service-lifecycle) or [MediaLibraryService](https://developer.android.com/guide/topics/media/session/medialibraryservice). First, create your `ExoPlayer` instance and then when building your [`CastPlayer`](https://developer.android.com/reference/androidx/media3/cast/CastPlayer) instance, set `ExoPlayer` as the local player instance. You can then switch media playback between your mobile and the Cast-enabled device from the media notification or the lock screen notification. Media3 uses the **Output Switcher** feature to handle player transfers when the output route changes from local to remote or from remote to local.
+ Figure 1: (a) Device chip on Media notification (b) Cast-enabled devices shown on tapping the device chip (c) Device chip on Lock screen notification
+
+
+
+### Kotlin
+
+```kotlin
+override fun onCreate() {
+ super.onCreate()
+
+ val exoPlayer = ExoPlayer.Builder(context).build()
+ val castPlayer = CastPlayer.Builder(context).setLocalPlayer(exoPlayer).build()
+
+ mediaSession = MediaSession.Builder(context, castPlayer).build()
+}
+
+
+```
+
+### Java
+
+```java
+@Override
+public void onCreate() {
+ super.onCreate();
+
+ ExoPlayer exoPlayer = new ExoPlayer.Builder(context).build();
+ CastPlayer castPlayer = new CastPlayer.Builder(context).setLocalPlayer(exoPlayer).build();
+
+ mediaSession =
+ new MediaSession.Builder(/* context= */ context, /* player= */ castPlayer).build();
+}
+
+
+```
+
+
+
+> [!IMPORTANT]
+> **Important:** The preceding code snippet shows the `onCreate` method of a `MediaSessionService`. In an `Activity`, players should be created in `onStart` or `onResume`.
+
+## Add UI elements
+
+Add a [`MediaRouteButton`](https://developer.android.com/reference/androidx/mediarouter/app/MediaRouteButton) to your app's UI. Tapping the [`MediaRouteButton`](https://developer.android.com/reference/androidx/mediarouter/app/MediaRouteButton) opens a dialog displaying a list of available Cast-enabled devices on the network. When the user selects a device, the media playback is transferred from the mobile to the selected receiver device. This section shows you how to add the button and listen for events to update your UI when playback switches between local and remote devices.
+
+### Set the MediaRouteButton
+
+There are four ways to add the [`MediaRouteButton`](https://developer.android.com/reference/androidx/mediarouter/app/MediaRouteButton) to your activity's UI. The best choice depends on your app's design and requirements.
+
+- **Compose UI**: Add a button composable.
+- **Views UI** :
+ - Add the button to the app bar menu.
+ - Add the button inside `PlayerView`.
+ - Add the button as a standard `View`.
+
+ Figure 2: (a) MediaRouteButton in menu bar, (b) as a View, (c) in PlayerView, and (d) Dialog of Cast-enabled devices.
+
+> [!IMPORTANT]
+> **Important:** To use the [`MediaRouteButton`](https://developer.android.com/reference/androidx/mediarouter/app/MediaRouteButton) in Views UI, the containing activity must be a subclass of `FragmentActivity`.
+
+> [!TIP]
+> **Tip:** These screenshots are from the [demo-session](https://github.com/androidx/media/tree/release/demos/session) apps in Media3. You can checkout the app to see an example of `CastPlayer` implementation.
+
+#### Add a Composable `MediaRouteButton` to the Player
+
+You can add the [`MediaRouteButton`](https://developer.android.com/reference/androidx/mediarouter/app/MediaRouteButton) Composable to your player's UI. For more information, see the [Compose](https://developer.android.com/media/media3/ui/compose) guide.
+
+
+
+```kotlin
+@Composable
+fun PlayerComposeView(player: Player, modifier: Modifier = Modifier) {
+ var controlsVisible by remember { mutableStateOf(false) }
+
+ Box(
+ modifier = modifier.clickable { controlsVisible = true },
+ contentAlignment = Alignment.Center,
+ ) {
+ PlayerSurface(player = player, modifier = modifier)
+ AnimatedVisibility(visible = controlsVisible, enter = fadeIn(), exit = fadeOut()) {
+ Box(modifier = Modifier.fillMaxSize()) {
+ MediaRouteButton(modifier = Modifier.align(Alignment.TopEnd))
+ PrimaryControls(player = player, modifier = Modifier.align(Alignment.Center))
+ }
+ }
+ }
+}
+
+@Composable
+fun PrimaryControls(player: Player, modifier: Modifier = Modifier) {
+ // ...
+}
+
+
+```
+
+
+
+#### Add the `MediaRouteButton` to the PlayerView
+
+You can add the [`MediaRouteButton`](https://developer.android.com/reference/androidx/mediarouter/app/MediaRouteButton) directly within the [PlayerView](https://developer.android.com/guide/topics/media/ui/playerview)'s UI controls. After setting the [MediaController](https://developer.android.com/guide/topics/media/session/mediacontroller) as the player for your `PlayerView`, provide a `MediaRouteButtonViewProvider` to display the Cast button on the Player.
+
+
+
+### Kotlin
+
+```kotlin
+override fun onStart() {
+ super.onStart()
+
+ playerView.player = mediaController
+ playerView.setMediaRouteButtonViewProvider(MediaRouteButtonViewProvider())
+}
+
+```
+
+### Java
+
+```java
+@Override
+public void onStart() {
+ super.onStart();
+
+ playerView.setPlayer(mediaController);
+ playerView.setMediaRouteButtonViewProvider(new MediaRouteButtonViewProvider());
+}
+
+```
+
+
+
+#### Add the `MediaRouteButton` to the app bar menu
+
+To set up a [`MediaRouteButton`](https://developer.android.com/reference/androidx/mediarouter/app/MediaRouteButton) in the app bar menu, create an XML menu and override `onCreateOptionsMenu` in your `Activity`.
+
+
+
+
+
+### Kotlin
+
+```kotlin
+override fun onCreateOptionsMenu(menu: Menu): Boolean {
+ // ...
+ menuInflater.inflate(R.menu.sample_media_route_button_menu, menu)
+ val menuItemFuture: ListenableFuture