pablitoarango/android-skills / migrations/migrate-xml-to-compose
migrate-xml-to-compose
VerifiedViews to Compose migration per Google's strategy: incremental order, ComposeView and AndroidView interop, layout and widget mappings, navigation and theming during migration. Use when converting XML layouts, Fragments or View screens to Compose, and when mixed screens apply insets twice, break nested scrolling, lose ComposeView state, or drift from the XML theme.
XML to Compose Migration
Sources of truth: Migration strategy, Compose in Views, Views in Compose, Other considerations, RecyclerView migration, CoordinatorLayout migration, Navigation migration, XML themes to Material 3, Nested scrolling interop, Interoperability testing.
1. Migration strategy
Migrate incrementally; Compose and Views coexist until the app is fully Compose.
- Build new features in Compose. New screens are Compose, hosted by the existing navigation (for example a Fragment with a
ComposeView). - Build a shared component library as you go: common composables and the theme in a shared UI module, so every migrated screen reuses them.
- Replace existing screens, simplest first (static screens such as welcome, confirmation, settings).
- Mixed screens migrate bottom-up: replace leaf elements one at a time until the whole screen is Compose.
- Remove Fragments and move navigation only when every destination is a screen-level composable. The end state is a single Activity with Compose navigation.
2. Migrating one screen
Prepare
- Protect behavior first. Google relies on UI tests to catch migration regressions. If the screen has none, write them against the View version before changing it; Espresso tests keep working when run with
createAndroidComposeRule(section 6). - Move to unidirectional data flow. Compose works with UDF; an MVP presenter or Fragment code calling setters on views should become a ViewModel exposing UI state, before or during the migration (
android-viewmodel).
Inventory the screen
Go through the layout and its Fragment or Activity and record:
- Displayed state and who sets it. For every value a View shows (text, checked, enabled, visibility, list items), find where it changes today: a binding expression, an observer calling setters, or the View's own internal state. A View owns such fields; a composable receives them. Each becomes a UI state field or hoisted state.
- User input. Every listener, watcher and adapter callback becomes an event lambda passed up to the route composable.
- Values shared with Views that stay. Decide which side owns them (section 5).
- Styling inputs. Explicit
styleattributes, theme attribute references, text appearances, color state lists and shape overlays. They move into the Compose theme, not into literals (section 7). - Views that stay Views. SDK Views with no Compose version (
AdView,WebView,SurfaceViewplayers) stay behindAndroidView. Rewrite custom Views in Compose, simplest first. For Google Maps, prefer Maps Compose, which providesGoogleMapand manages its map lifecycle. - Structure defined by resources. Reused or lazily inflated layout files, size-qualified layout folders, embedded Fragments, binding adapters.
mappings.mdcovers each. - Scroll and inset coordination.
CoordinatorLayoutbehaviors, scrolling parents that will contain aComposeView,fitsSystemWindows. These need scroll behaviors, nested scroll interop or explicit inset consumption (section 4). - Navigation coupling.
findNavController()calls and arguments. Arguments carrying complex objects should become IDs loaded from the data layer.
Convert
- Map containers, widgets and attributes with
mappings.md. - Split into a route composable (gets the ViewModel, collects state) and a stateless screen composable (
compose-ui). - Replace
visibilitytoggles with conditional composition: a composable is either in the composition or not. - Keep the Fragment as a thin
ComposeViewhost while Fragment navigation remains.
Check the result
- The UI tests written before the change pass against the Compose version.
- Rendering matches the View version for the same data, compared with screenshot tests (
android-testing) or previews in light and dark theme, large font scale and every supported window size. - Every theme value matches the old XML theme; no value was invented or hardcoded.
rememberSaveablestate and ViewModel state survive rotation and process recreation (StateRestorationTester, seecompose-testing).- TalkBack labels, merged rows, touch targets and traversal order are correct (
compose-accessibility). - Where Views and Compose share the hierarchy, insets are consumed once and nested scrolling hands over between them.
- The ViewModel keeps the same owner and scope as before.
- Dead code is gone: the layout file, adapters and ViewHolders, binding adapters, styles and dimensions nothing references, and the view binding or data binding build features once no layout needs them.
3. Mapping layouts, widgets and attributes
When converting a layout, read mappings.md. It follows the structure of the Compose docs: layout containers; scrolling, lists and paging; text and input; images; Material components; attributes to modifiers; resources and layout reuse.
4. Interop
Compose inside Views
In a Fragment, always set the composition strategy so the composition follows the Fragment's view lifecycle:
class ArticleFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View = ComposeView(requireContext()).apply {
setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
setContent {
AppTheme {
ArticleRoute()
}
}
}
}
Where the ComposeView lives | ViewCompositionStrategy |
|---|---|
| A Fragment's view | DisposeOnViewTreeLifecycleDestroyed, or DisposeOnLifecycleDestroyed(viewLifecycleOwner) |
| A View whose lifecycle owner is not known yet | DisposeOnViewTreeLifecycleDestroyed |
An Activity layout, or a RecyclerView item | DisposeOnDetachedFromWindowOrReleasedFromPool (the default); it replaces DisposeOnDetachedFromWindow |
- Give every
ComposeViewon a screen a unique ID (define IDs inres/values/ids.xmlfor programmatic views) so saved state works. - Preview a composable inside the XML Layout Editor with
tools:composableNameon theComposeView. - Insets: each
ComposeViewconsumes all insets by default. Consume them on the side that owns the outermost layout: with a View root, setconsumeWindowInsets = falseon theComposeView; with a Compose root, consume in Compose and padAndroidViews. - Nested scrolling: a
ComposeViewinside a cooperating View parent such asCoordinatorLayoutneedsModifier.nestedScroll(rememberNestedScrollInteropConnection())on its content.RecyclerViewandViewPager2do not implementNestedScrollingParent3, so continuous scrolling from a Compose child into them is not possible. See nested scrolling interop. - Shared components: wrap a composable used from XML layouts in an
AbstractComposeViewsubclass that exposes its inputs asmutableStateOfproperties and wrapsContent()in the app theme. - When a
ComposeViewlives inside aRecyclerView, use RecyclerView 1.3.0 or newer.
Views inside Compose
@Composable
fun WebContent(url: String, modifier: Modifier = Modifier) {
AndroidView(
factory = { context -> WebView(context) },
update = { webView ->
if (webView.url != url) webView.loadUrl(url)
},
onRelease = { webView -> webView.destroy() },
modifier = modifier,
)
}
The WebView API example shows creation, input updates and cleanup; configure navigation and other browser behavior for the app's requirements.
factoryruns once, on the UI thread: create the View and set constant properties there. Prefer creating the View there over holding it inrememberoutsideAndroidView.updateruns right afterfactoryand again whenever state it reads changes.- By default, Views are discarded and recreated inside lazy layouts. Pass a non-null
onReset = { view -> ... }to opt in to reuse; it runs before the View is reused and should clear transient state.onReleaseruns once when the View leaves the composition for good. AndroidViewdoes not clip its View to its bounds; callView.setClipToOutlinewhere needed (common forSurfaceView).- Nested scrolling: for a scrolling View (such as a
RecyclerView) inside a scrollable composable or one usingModifier.nestedScroll, callViewCompat.setNestedScrollingEnabled(view, true)on the root View infactoryso its deltas reach the Compose parent. In the other direction,rememberNestedScrollInteropConnection()only forwards deltas from scrollable content; a plainBoxorColumnalso needs a scrollable modifier. - Use
AndroidViewBinding(androidx.compose.ui:ui-viewbinding) only for small legacy XML layouts during migration, not full screens. - Use
AndroidFragment<MyFragment>()only as a temporary step while a screen still depends on a Fragment. In a pager, cap offscreen pages with itsmaxLifecycleparameter (Fragment 1.9.0 or newer). - Framework objects stay reachable through
LocalContext,LocalConfigurationandLocalView.
5. State and navigation during migration
- ViewModel: obtain it only in the route composable; collect with
collectAsStateWithLifecycle()(orobserveAsState()forLiveDatanot yet converted toStateFlow). Never pass it to child composables.viewModel()returns the same instance for every composable under one Activity or Fragment, unless the composable is a navigation destination. - Click listeners become event lambdas.
- Shared state between Views and Compose: prefer a ViewModel both read. When state is tied to a UI element, the side closer to the root owns it: if Compose owns it, publish to View code with
SideEffect; if a View owns it, hold it inmutableStateOfso Compose observes changes. - Navigation: one navigation setup cannot mix Fragment and composable destinations. Keep Fragment-based Navigation while any destination is still a Fragment. Once every destination is a screen composable, move to a single Activity with Navigation 3 (see
compose-navigation) and delete the Fragments, their layouts and navigation XML.
6. Testing
- Use
createAndroidComposeRule<YourActivity>()for screens mixing Views and Compose. In the same test, Espresso'sonViewfinds Views and the rule's finders locate composables (compose-testing). - For a composable inside a
RecyclerViewrow or aViewPagerpage, locate the container with Espresso first, then scope the Compose search to it withonRootWithViewInteraction(viewInteraction)(experimental,ui-test1.12.0 or newer). - UiAutomator sees composables by resource ID only after setting
testTagsAsResourceId = truein semantics near the root. - Add UI tests before migrating a screen when none exist, so the migration is covered.
7. Theming
- Wrap all Compose content in the app's theme before any Material composable; Material components behave in undefined ways without a
MaterialTheme. Target Material 3 when the design system allows it. - During migration the XML theme and the Compose theme are two sources of truth; change both until the XML theme can be deleted.
- Colors map by role, not by hex name:
colorPrimary→primary,colorOnPrimary→onPrimary,colorSurface→surface,colorOnSurface→onSurface,colorError→error,android:colorBackground→background. Legacy roles need a decision:colorPrimaryVariant/colorPrimaryDark→primaryContainerorsecondary,colorAccent→secondaryortertiary. Migrate light and dark schemes; Material Theme Builder can generate them. - Typography:
TextAppearance.Material3.BodyMediumbecomesMaterialTheme.typography.bodyMedium, and so on for each role; custom text appearances become aTypographyobject. - Shapes:
ShapeAppearanceoverlays become aShapesobject passed toMaterialTheme. - Styles have no direct Compose equivalent. Translate a component style into that component's parameters (
ButtonDefaults.buttonColors(...),shape,contentPadding), or into a named composable such asPrimaryActionButtonwhen the style is reused. colorResourceworks for static colors only; it flattens color state lists.- Copy values from the existing XML theme. Do not invent new ones or hardcode them in composables.
8. Checklist
- The screen was picked by the migration order and covered by UI tests before it changed.
- Every displayed value comes from UI state or hoisted state; no View-style setters or binding code remain in the migrated part.
- Route composable plus stateless screen composable; ViewModel only in the route; state collected with
collectAsStateWithLifecycle(). - Colors, typography and shapes come from the Compose theme and match the XML theme.
- Interop is configured: composition strategy per host, unique
ComposeViewIDs, insets consumed once, nested scroll interop where Views and Compose scroll together. -
AndroidViewonly for Views without a Compose equivalent, withonResetin lazy layouts and cleanup inonRelease. - Fragment-based navigation stays until every destination is a composable.
- UI tests, visual comparison, state restoration and accessibility checks pass.
- Layouts, adapters, binding code and resources made unused by the migration are deleted.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack." | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |