Yokan / rebuild
Course 1 8624561

19-xml-to-compose-migration.md

.codex/skills/compose-kotlin-agent-skills/references/19-xml-to-compose-migration.md

documentation / design asset209 lines
1---2name: xml-to-compose-migration3description: >4  XML Views to Jetpack Compose migration — mapping table, ComposeView interop,5  ViewBinding removal, RxJava to Coroutines, checklist and pitfalls. Use when migrating legacy UI.6version: "2.2.0"7updated: "2026-05-21"8---910# XML → Compose Migration1112## XML → Compose mapping table1314| XML / View | Compose equivalent |15|---|---|16| `LinearLayout vertical` | `Column` |17| `LinearLayout horizontal` | `Row` |18| `FrameLayout` | `Box` |19| `ScrollView` | `Column` + `verticalScroll` or `LazyColumn` |20| `RecyclerView` | `LazyColumn` / `LazyRow` / `LazyVerticalGrid` |21| `TextView` | `Text` |22| `EditText` | `TextField` / `OutlinedTextField` |23| `ImageView` | `Image` / `AsyncImage` (Coil) |24| `Button` | `Button` / `TextButton` |25| `Toolbar` / `AppBarLayout` | `TopAppBar` + `Scaffold` |26| `BottomNavigationView` | `NavigationBar` |27| `Fragment` | Composable destination + `NavHost` |28| `ViewModel` + `LiveData` | `ViewModel` + `StateFlow` |29| `findViewById` | State + parameters |30| `Data Binding` | State hoisting + `collectAsStateWithLifecycle` |31| `ViewBinding` | Remove — pass state to Composables |3233---3435## WRONG / RIGHT 1 — ComposeView without dispose strategy3637```kotlin38// WRONG — composition survives after fragment destroy39class LegacyFragment : Fragment() {40    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, saved: Bundle?) =41        ComposeView(requireContext()).apply {42            setContent { LegacyScreen() }43        }44}4546// RIGHT — ViewCompositionStrategy tied to lifecycle47class LegacyFragment : Fragment() {48    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, saved: Bundle?) =49        ComposeView(requireContext()).apply {50            setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)51            setContent { LegacyScreen() }52        }53}54```5556---5758## WRONG / RIGHT 2 — Keeping ViewBinding alongside Compose in same screen5960```kotlin61// WRONG — dual UI systems, state split62class ProfileActivity : AppCompatActivity() {63    private lateinit var binding: ActivityProfileBinding64    override fun onCreate(savedInstanceState: Bundle?) {65        super.onCreate(savedInstanceState)66        binding = ActivityProfileBinding.inflate(layoutInflater)67        setContentView(binding.root)68        binding.composeHost.setContent { ProfileHeader() }  // half XML half Compose69        binding.nameText.text = viewModel.name  // duplicate state70    }71}7273// RIGHT — full Compose Activity74class ProfileActivity : ComponentActivity() {75    override fun onCreate(savedInstanceState: Bundle?) {76        enableEdgeToEdge()77        super.onCreate(savedInstanceState)78        setContent {79            AppTheme {80                ProfileScreen()81            }82        }83    }84}85```8687---8889## WRONG / RIGHT 3 — Migrating LiveData observers to Compose9091```kotlin92// WRONG — observeAsState() from LiveData in new Compose code93@Composable94fun ProfileScreen(vm: ProfileViewModel) {95    val name by vm.nameLiveData.observeAsState("")96    Text(name)97}9899// RIGHT — migrate VM to StateFlow first100@Composable101fun ProfileScreen(vm: ProfileViewModel = hiltViewModel()) {102    val state by vm.state.collectAsStateWithLifecycle()103    ProfileContent(state = state, onEvent = vm::onEvent)104}105106class ProfileViewModel @Inject constructor(repo: ProfileRepository) : ViewModel() {107    private val _state = MutableStateFlow(ProfileUiState())108    val state: StateFlow<ProfileUiState> = _state.asStateFlow()109}110```111112---113114## WRONG / RIGHT 4 — RxJava chain left in repository during UI migration115116```kotlin117// WRONG — RxJava in data layer, Compose UI expects coroutines118class UserRepository(private val api: Api) {119    fun loadUser(): Observable<User> =120        api.getUser().subscribeOn(Schedulers.io())121}122123// RIGHT — suspend + Flow migration path124interface UserRepository {125    fun observeUser(id: String): Flow<User>126}127128class UserRepositoryImpl @Inject constructor(129    private val api: Api,130    private val dao: UserDao131) : UserRepository {132    override fun observeUser(id: String): Flow<User> =133        dao.observeUser(id).map { it.toDomain() }134135    suspend fun refresh(id: String) {136        val dto = api.fetchUser(id)137        dao.upsert(dto.toEntity())138    }139}140```141142---143144## WRONG / RIGHT 5 — RecyclerView.Adapter logic copied into LazyColumn items block145146```kotlin147// WRONG — bind logic + click + image load inside item lambda148@Composable149fun UserList(users: List<User>) {150    LazyColumn {151        items(users) { user ->152            val bitmap = loadBitmap(user.avatarUrl)  // IO in composition153            Row(Modifier.clickable { navigate(user) }) {154                Image(bitmap.asImageBitmap(), null)155                Text(user.name)156            }157        }158    }159}160161// RIGHT — stateless item composable, events up, Coil for images162@Composable163fun UserList(164    users: List<UserUi>,165    onUserClick: (String) -> Unit,166    modifier: Modifier = Modifier167) {168    LazyColumn(modifier = modifier) {169        items(170            items = users,171            key = { it.id },172            contentType = { "user" }173        ) { user ->174            UserRow(user = user, onClick = { onUserClick(user.id) })175        }176    }177}178```179180---181182## Migration checklist183184- [ ] Inventory screens — prioritize leaf screens (settings, about) before root nav185- [ ] Replace `Fragment` + XML with Composable destinations one at a time186- [ ] Migrate `LiveData` → `StateFlow` in ViewModel before touching UI187- [ ] Migrate RxJava → suspend/Flow in repositories188- [ ] Remove ViewBinding/DataBinding generated code per migrated screen189- [ ] Add `enableEdgeToEdge()` when converting Activities190- [ ] Replace `RecyclerView` diff logic with stable `key` + immutable lists191- [ ] Run Compose UI tests for migrated screens192- [ ] Delete unused XML layouts + drawables after each screen lands193194## Interop strategy (strangler fig)1951961. **Phase A** — `ComposeView` in XML host for one component (toolbar, bottom sheet)1972. **Phase B** — Full screen Compose inside existing Activity1983. **Phase C** — Single `ComponentActivity` + Navigation Compose; delete XML nav graphs1994. **Phase D** — Remove AppCompat theme XML where Material3 Compose theme replaces it200201## Common pitfalls202203| Pitfall | Fix |204|---|---|205| State in XML and Compose | Single source in ViewModel `StateFlow` |206| `remember` for screen state | Hoist to ViewModel |207| Missing `key` after RecyclerView migration | `items(list, key = { it.id })` |208| Config change loses state | ViewModel + `rememberSaveable` only for UI-local state |209| Custom Views without Compose equivalent | `AndroidView` factory — migrate last |210

Search chapters, reference and source filenames.