Skip to content
Commitwise
Menu
Android Development

Views and Fragments: the UI toolkit before Compose

Read and fix the View-based code most Android apps still contain. XML layouts, ConstraintLayout and ViewBinding, RecyclerView with ListAdapter and DiffUtil, how views measure and draw, the Fragment lifecycle and its separate view lifecycle, binding leaks, arguments, FragmentManager transactions and results, and mixing Views with Compose during a migration.

intermediate

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

A list where ticking one checkbox ticks another one ten rows down. A screen that leaks memory every time the user goes back. A crash that only happens after rotating the phone on a screen opened with a fragment. New Android UI is written in Compose, but these bugs come from the toolkit underneath most existing apps: Views and Fragments.

If you join a team with an app older than a few years, you’ll work in XML layouts and Fragments, and you’ll migrate them to Compose one screen at a time. Interviewers know this, so “explain the Fragment lifecycle” and “how does RecyclerView recycle views?” are still standard questions. This lesson assumes you know Compose basics and the Activity lifecycle.

New to some of these? Open what you need, or skip ahead.

Basics:What is a View?

A View is an object that draws a rectangle of the screen and handles touches in it: a TextView, a Button, an ImageView. Views are arranged in a tree: a ViewGroup (like LinearLayout or ConstraintLayout) contains child views and decides where they go. Unlike Compose, views are long-lived objects you change directly: textView.text = "Hi".

Basics:What is a Fragment?

A Fragment is a reusable piece of a screen with its own lifecycle, hosted inside an Activity. Before Compose, apps used one Activity with many Fragments so that screens could be swapped, combined on tablets and kept on a back stack. Fragments can also host Compose content.

Part Not started

Views, layouts and RecyclerView

A View-based screen has two halves: an XML layout that describes the tree of views, and Kotlin code that finds those views and fills them with data.

  • ConstraintLayout positions views relative to each other and to the parent (“below the title, 16dp from the start”), which keeps the tree flat. LinearLayout stacks children in a row or column.
  • ViewBinding generates a class per layout with a typed property for each view that has an id: binding.title.text = recipe.name. It replaced findViewById and the old Kotlin synthetics, which were removed in Kotlin 1.8.

Long lists use RecyclerView. Instead of creating a view for each of 1,000 rows, it creates only enough ViewHolders to fill the screen and a few extra, and recycles them: when a row scrolls off the top, its ViewHolder is reused for the row appearing at the bottom, and onBindViewHolder fills it with the new row’s data.

That reuse is the source of the most common RecyclerView bug: a recycled ViewHolder still shows whatever the previous row left in it, unless you set every property in onBindViewHolder.

Rendering runs in three passes over the tree: measure (each parent asks children how big they want to be under MeasureSpec constraints: EXACTLY, AT_MOST, UNSPECIFIED), layout (parents position children) and draw. invalidate() schedules only a redraw; requestLayout() re-runs measure and layout up the tree, which is far more expensive, and calling it on every frame or every bind causes jank. Nested LinearLayout weights and RelativeLayout measure children twice per level, so deep nesting multiplies measure passes; ConstraintLayout keeps trees flat. Custom views override onMeasure (call setMeasuredDimension), onLayout for groups and onDraw (allocate no objects there). RecyclerView: a LayoutManager places items, ViewHolders are pooled per view type in a RecycledViewPool (shareable between nested lists), and ListAdapter diffs submitted lists with DiffUtil on a background thread (AsyncListDiffer), producing item-level animations instead of notifyDataSetChanged()’s full rebind; DiffUtil.ItemCallback needs a stable identity in areItemsTheSame and a content check in areContentsTheSame, and getChangePayload enables partial rebinds. setHasFixedSize(true) avoids re-measuring the RecyclerView when only content changes. View state survives configuration changes through onSaveInstanceState only for views with an id.

class RecipeAdapter(
    private val onFavorite: (Recipe, Boolean) -> Unit,
) : ListAdapter<Recipe, RecipeAdapter.Holder>(Diff) {

    class Holder(val binding: ItemRecipeBinding) : RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        Holder(ItemRecipeBinding.inflate(LayoutInflater.from(parent.context), parent, false))

    override fun onBindViewHolder(holder: Holder, position: Int) {
        val recipe = getItem(position)
        holder.binding.title.text = recipe.name
        holder.binding.favorite.setOnCheckedChangeListener(null)       // don't fire for the old row
        holder.binding.favorite.isChecked = recipe.isFavorite           // set every property, every time
        holder.binding.favorite.setOnCheckedChangeListener { _, checked -> onFavorite(recipe, checked) }
    }

    object Diff : DiffUtil.ItemCallback<Recipe>() {
        override fun areItemsTheSame(old: Recipe, new: Recipe) = old.id == new.id
        override fun areContentsTheSame(old: Recipe, new: Recipe) = old == new
    }
}

// In the screen: adapter.submitList(recipes)   // diffs on a background thread and animates the changes
<!-- res/layout/item_recipe.xml -->
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp">

    <TextView
        android:id="@+id/title"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toStartOf="@id/favorite"
        app:layout_constraintTop_toTopOf="parent" />

    <CheckBox
        android:id="@+id/favorite"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Predict the output

A RecyclerView shows 1,000 rows; about 10 fit on screen. The user scrolls from the top to the bottom. Roughly how many times is onCreateViewHolder called?

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
    created++
    return Holder(ItemRecipeBinding.inflate(LayoutInflater.from(parent.context), parent, false))
}

The checkbox that ticks itself

Spot the bugFavoriting one recipe favorites another one further down

Tap the line with the bug.

override fun onBindViewHolder(holder: Holder, position: Int) {
    val recipe = getItem(position)
    holder.binding.title.text = recipe.name
    if (recipe.isFavorite) {
        holder.binding.favorite.isChecked = true
    }
    holder.binding.favorite.setOnCheckedChangeListener { _, checked ->
        onFavorite(recipe, checked)
    }
}

Deep diveinvalidate() vs requestLayout()Interview favorite

invalidate() marks a view as needing to be redrawn: on the next frame its onDraw runs again, with the same size and position. Use it when only the appearance changes: a color, a progress arc, a custom chart’s highlighted bar.

requestLayout() marks the view and all its ancestors as needing measure and layout: on the next frame, the whole path to the root is measured and laid out again, and siblings may move. Use it when the view’s size might change: new text in a wrap_content view, a different image size. Setters like TextView.setText call it for you when needed. Calling requestLayout() from onLayout or on every animation frame forces layout passes on every frame, which shows up in a Perfetto trace as long “measure” and “layout” slices; animate translationX, alpha or scaleX instead, which only redraw.

  • Measure (MeasureSpec), layout, draw; invalidate = redraw, requestLayout = re-measure up the tree. Flat ConstraintLayout trees; nested weights and RelativeLayout measure twice per level.
  • RecyclerView: pooled ViewHolders per view type, bind everything (state, listeners, images), ListAdapter + DiffUtil with stable ids and payloads instead of notifyDataSetChanged.
  • ViewBinding over findViewById; synthetics are gone. View state is saved only for views with ids.

Check this part

  1. Why must onBindViewHolder set every property of the row, even ones that look like defaults?

  2. What replaced findViewById and Kotlin synthetics?

  3. A custom view only changes color. Which call is enough?

  4. What does ListAdapter with DiffUtil give you over notifyDataSetChanged()?

Layouts are XML view trees, preferably flat with ConstraintLayout, accessed through ViewBinding. RecyclerView reuses a few ViewHolders for many rows, so bind every piece of state in onBindViewHolder, and give it data through ListAdapter with DiffUtil instead of notifyDataSetChanged. invalidate redraws, requestLayout re-measures.

Part Not started

Fragments and their two lifecycles

The most important thing about Fragments: a Fragment has two lifecycles, one for the Fragment object and one for its view.

When the user navigates from a list to a detail screen, the list Fragment goes onto the back stack. Its view is destroyed (onDestroyView) to save memory, but the Fragment object stays. When the user presses Back, the same Fragment gets a brand-new view (onCreateView again).

Three rules follow from that:

  • Clear the binding in onDestroyView. Otherwise the Fragment keeps the whole old view tree in memory while it sits in the back stack.
  • Observe data with viewLifecycleOwner, not with the Fragment itself (this). Observers tied to the Fragment survive across views, so after coming back you get two observers updating a view that may not exist.
  • Never pass data through the constructor. After rotation or process death, Android recreates the Fragment with its empty constructor, and the data is gone. Put it in arguments (a Bundle), which are saved and restored.

Fragment states: onAttach → onCreate → onCreateView → onViewCreated → onStart → onResume, and back down through onDestroyView → onDestroy → onDetach; the view lifecycle (viewLifecycleOwner, getViewLifecycleOwnerLiveData()) spans onCreateView to onDestroyView, and onActivityCreated is deprecated. Collect flows with viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(STARTED) { … } }. The FragmentManager recreates fragments reflectively after configuration changes and process death, hence arguments and, for dependencies, a FragmentFactory (or Hilt’s @AndroidEntryPoint, which avoids constructor parameters by injecting fields in onAttach). Transactions: commit() is asynchronous, commitNow() synchronous (not allowed with addToBackStack); committing after onSaveInstanceState throws IllegalStateException because the state would be lost, and commitAllowingStateLoss() only hides that. setReorderingAllowed(true) is required for correct animations and is what Navigation uses. Communication: shared ViewModel via activityViewModels()/navigation-graph-scoped view models, the Fragment Result API (setFragmentResult/setFragmentResultListener) for one-off results, never direct references to other fragments or casting activity. Child fragments use childFragmentManager; FragmentStateAdapter in ViewPager2 keeps off-screen pages at STARTED via setMaxLifecycle.

class RecipeFragment : Fragment(R.layout.fragment_recipe) {

    private var _binding: FragmentRecipeBinding? = null
    private val binding get() = _binding!!                 // valid only between onViewCreated and onDestroyView
    private val viewModel: RecipeViewModel by viewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        _binding = FragmentRecipeBinding.bind(view)
        val recipeId = requireArguments().getLong(ARG_ID)  // survives rotation and process death
        viewModel.load(recipeId)

        viewLifecycleOwner.lifecycleScope.launch {
            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.state.collect { binding.title.text = it.name }
            }
        }
    }

    override fun onDestroyView() {
        _binding = null                                     // the Fragment may live on in the back stack
        super.onDestroyView()
    }

    companion object {
        private const val ARG_ID = "recipeId"
        fun newInstance(id: Long) = RecipeFragment().apply { arguments = bundleOf(ARG_ID to id) }
    }
}

Predict the output

A Fragment is created as RecipeFragment(recipeId = 42), with the id passed through a constructor parameter. The user rotates the phone. What happens?

class RecipeFragment(private val recipeId: Long) : Fragment(R.layout.fragment_recipe)

// Opening it:
supportFragmentManager.commit {
    replace(R.id.container, RecipeFragment(recipeId = 42))
    addToBackStack(null)
}

Coming back crashes the screen

Spot the bugBack from details, then a crash or doubled updates

Tap the line with the bug.

class RecipeListFragment : Fragment(R.layout.fragment_list) {
    private var _binding: FragmentListBinding? = null
    private val binding get() = _binding!!

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        _binding = FragmentListBinding.bind(view)
        lifecycleScope.launch {
            viewModel.recipes.collect { adapter.submitList(it); binding.count.text = "${it.size}" }
        }
    }

    override fun onDestroyView() {
        _binding = null
        super.onDestroyView()
    }
}

Returning a result

// In the list screen, register once (in onCreate or onViewCreated):
childFragmentManager.setFragmentResultListener("filter", viewLifecycleOwner) { _, bundle ->
    viewModel.applyFilter(bundle.getString("cuisine"))
}

// In the dialog (shown with childFragmentManager):
setFragmentResult("filter", bundleOf("cuisine" to selectedCuisine))
dismiss()

The listener is delivered only when the listening lifecycle is at least STARTED, and the latest result per key is kept until then, so a result set while the list is in the background arrives when it comes back. Use the same FragmentManager on both sides: the parent’s childFragmentManager for child fragments and dialogs, the shared parentFragmentManager for siblings.

Deep diveCan not perform this action after onSaveInstanceStateInterview favorite

Once an Activity has called onSaveInstanceState, the FragmentManager’s state has been written into the saved bundle. A transaction committed after that point wouldn’t be in the bundle, so if the process died and was restored, the UI would silently differ from what the user last saw. Rather than allow that, commit() throws IllegalStateException.

It typically happens when an async callback (a network response, a timer) navigates after the user pressed Home. Fixes, best first: drive navigation from state collected with repeatOnLifecycle(STARTED), so it only runs while the UI is started; use the Navigation component, which defers such actions; and use commitAllowingStateLoss() only for transactions whose loss genuinely doesn’t matter, like dismissing a transient dialog.

  • Two lifecycles: Fragment vs view (onCreateView…onDestroyView). Null the binding in onDestroyView; observe with viewLifecycleOwner + repeatOnLifecycle.
  • Recreated reflectively: arguments for data, FragmentFactory (or Hilt) for dependencies.
  • commit after onSaveInstanceState throws; commitNow can’t use the back stack; setReorderingAllowed(true).
  • Communicate through shared ViewModels and the Fragment Result API, not references to other fragments.

Check this part

  1. Why set the binding to null in onDestroyView?

  2. How should a Fragment receive the id of the recipe to show?

  3. Which lifecycle owner should a Fragment use to collect UI state?

  4. Why does commit() throw after onSaveInstanceState?

A Fragment outlives its view: in the back stack it keeps existing while the view is destroyed, so clear the binding in onDestroyView and observe data with viewLifecycleOwner. The system recreates fragments with a no-argument constructor, so pass data through arguments. Don't commit transactions after state is saved; use the Fragment Result API to return values.

Part Not started

Mixing Views and Compose

Nobody rewrites a big app in one go. Teams migrate one screen or one component at a time, so for years an app contains both toolkits. Two bridges make that work:

  • ComposeView is a View that hosts Compose. Put it in an XML layout or return it from a Fragment’s onCreateView, and call setContent { … }.
  • AndroidView is a composable that hosts a View. Use it for things that exist only as Views: MapView, WebView, an ad SDK, an old custom chart.

A common path: new screens in Compose, then existing screens converted when they need significant changes anyway, starting with simple leaf components (a card, a button style) and ending with navigation.

Inside a Fragment, give the ComposeView ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed so the composition lives exactly as long as the Fragment’s view (the default disposes on window detach, which fits plain Views and RecyclerView items). AndroidView(factory, update): factory runs once to create the view, update runs after every recomposition that reads state used in it, so it must be idempotent and cheap; onReset/onRelease (in lazy lists) let views be reused or cleaned up. Share one design system: the Material Components bridge or a Compose theme that reads the same tokens, so mixed screens look identical. Keep the screen’s ViewModel and state the same while swapping its UI layer, so the migration is a pure UI change; test with screenshot tests before and after. Performance traps: Compose in RecyclerView items (fine since Compose 1.2’s pooling-aware strategy, but measure), and deeply nested interop (Views inside Compose inside Views) which defeats both toolkits’ optimizations. The interview question “how would you migrate a large app to Compose?” wants exactly this: incremental, leaf-first or new-screens-first, shared theme and ViewModels, metrics (APK size, startup, jank) watched throughout.

// A Fragment whose UI is now Compose, still hosted by the old navigation
class RecipeFragment : Fragment() {
    private val viewModel: RecipeViewModel by viewModels()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) =
        ComposeView(requireContext()).apply {
            setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
            setContent {
                AppTheme {
                    val state by viewModel.state.collectAsStateWithLifecycle()
                    RecipeScreen(state, onFavorite = viewModel::toggleFavorite)
                }
            }
        }
}

// A View-only component inside Compose
@Composable
fun RecipeVideo(url: String, modifier: Modifier = Modifier) {
    AndroidView(
        factory = { context -> PlayerView(context) },                  // created once
        update = { view -> view.player = playerFor(url) },             // runs again when url changes
        modifier = modifier,
    )
}

A page that keeps reloading

Spot the bugThe help page reloads whenever the user types

Tap the line with the bug.

@Composable
fun HelpScreen(question: String, onQuestionChange: (String) -> Unit) {
    Column {
        TextField(value = question, onValueChange = onQuestionChange)
        AndroidView(
            factory = { context -> WebView(context) },
            update = { webView ->
                webView.loadUrl("https://help.example.com/?q=" + question)
            },
        )
    }
}

Deep diveMigrating a large View-based app: an interview answerInterview favorite

A good answer is a plan, not a preference. Start with new screens in Compose and a shared theme that maps the existing design tokens, so nothing looks different. Then convert leaf components that are reused everywhere (buttons, cards, empty states) and screens that are about to change anyway, keeping their ViewModels untouched so each step is a pure UI change. Navigation last: Fragments with ComposeView keep working with the existing Navigation graph until most screens are Compose, and only then does a move to Navigation Compose pay off.

Guard rails: screenshot tests on converted screens, macrobenchmarks for startup and scroll jank (Compose adds code and needs a baseline profile), APK size tracking, and a rule that no new XML layouts are added. Mention the people side too: pairing and a small internal guide get a team of View experts productive faster than a rewrite mandate.

  • ComposeView in Fragments with DisposeOnViewTreeLifecycleDestroyed; AndroidView factory once, update idempotent (runs on recomposition), onReset/onRelease in lazy lists.
  • Migrate incrementally: new screens, then leaf components and changing screens, navigation last; same ViewModels and theme tokens.
  • Watch screenshot tests, startup and jank benchmarks, APK size; avoid deep View-in-Compose-in-View nesting.

Check this part

  1. How do you show a MapView inside a Compose screen?

  2. What is the usual way to move a large app to Compose?

  3. When does AndroidView's update block run?

  4. Which ViewCompositionStrategy fits a ComposeView returned from a Fragment's onCreateView?

Migrate screen by screen: ComposeView puts Compose inside Views and Fragments (dispose it with the view's lifecycle), AndroidView puts a View inside Compose (create it in factory, update it in update, which runs on every recomposition). Keep one theme and one ViewModel per screen during the move.

Key takeaways

  • Views are long-lived objects in a tree; layouts are XML, accessed through ViewBinding, kept flat with ConstraintLayout.
  • RecyclerView recycles a few ViewHolders: set every property in onBindViewHolder, and use ListAdapter with DiffUtil.
  • A Fragment outlives its view: clear the binding in onDestroyView and observe with viewLifecycleOwner.
  • Pass data to Fragments in arguments, never constructor parameters.
  • Migrate to Compose gradually with ComposeView and AndroidView.
  • Know measure, layout and draw, and the cost difference between invalidate and requestLayout.
  • RecyclerView performance: view types and pools, stable diffs and payloads, no layout work in bind.
  • Fragments: two lifecycles, reflective recreation (arguments, FragmentFactory), state-loss rules, Fragment Result API.
  • Migration is an engineering plan: shared theme and ViewModels, leaf-first, navigation last, measured with benchmarks.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.