Bird
Raised Fist0
Android Kotlinmobile~20 mins

Compose with existing Views (interop) in Android Kotlin - Mini App: Build & Ship

Choose your learning style10 modes available
Build: ComposeInteropScreen
A screen that shows a Compose UI with a traditional Android Button inside it using interop.
Target UI
-------------------------
| ComposeInteropScreen   |
|-----------------------|
|                       |
|  [Compose Text Here]   |
|                       |
|  [Android Button]      |
|                       |
-------------------------
Use Compose to create a screen with a Text composable displaying 'Hello from Compose!'
Below the Text, embed a traditional Android Button using AndroidView interop.
The Button should have the label 'Click Me' and show a Toast message 'Button clicked!' when tapped.
Starter Code
Android Kotlin
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView

class ComposeInteropScreen : ComponentActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      ComposeInteropContent()
    }
  }
}

@Composable
fun ComposeInteropContent() {
  val context = LocalContext.current
  Column(modifier = Modifier.padding(16.dp)) {
    Text(text = "Hello from Compose!")
    // TODO: Add AndroidView with Button here
  }
}
Task 1
Task 2
Task 3
Solution
Android Kotlin
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView

class ComposeInteropScreen : ComponentActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      ComposeInteropContent()
    }
  }
}

@Composable
fun ComposeInteropContent() {
  val context = LocalContext.current
  Column(modifier = Modifier.padding(16.dp)) {
    Text(text = "Hello from Compose!")
    AndroidView(factory = { ctx ->
      Button(ctx).apply {
        text = "Click Me"
        setOnClickListener {
          Toast.makeText(ctx, "Button clicked!", Toast.LENGTH_SHORT).show()
        }
      }
    }, modifier = Modifier.padding(top = 16.dp))
  }
}

This solution uses the AndroidView composable to embed a traditional Android Button inside a Compose layout.

The factory lambda creates the Button and sets its label to "Click Me".

We add a click listener to show a Toast message when the button is tapped.

This shows how Compose can interoperate with existing Android Views easily.

Final Result
Completed Screen
-------------------------
| ComposeInteropScreen   |
|-----------------------|
|                       |
|  Hello from Compose!   |
|                       |
|  [Click Me Button]     |
|                       |
-------------------------
When user taps the 'Click Me' button, a Toast message 'Button clicked!' appears briefly at the bottom.
Stretch Goal
Add a second Android Button below the first that changes the Compose Text to 'Button 2 clicked!' when tapped.
💡 Hint
Use a Compose state variable to hold the text and update it inside the second Button's onClickListener.

Practice

(1/5)
1. What is the main purpose of using AndroidView in Jetpack Compose?
easy
A. To create animations in Compose
B. To convert Compose UI elements into XML layouts
C. To replace all Views with Compose components automatically
D. To embed traditional Android Views inside a Compose UI

Solution

  1. Step 1: Understand AndroidView role

    AndroidView allows embedding existing Android Views inside Compose UI, enabling reuse of legacy UI parts.
  2. Step 2: Compare options

    Creating animations, converting Compose UI elements into XML layouts, and automatically replacing all Views with Compose components do not describe embedding Views inside Compose. Only embedding traditional Android Views inside a Compose UI correctly states the purpose.
  3. Final Answer:

    To embed traditional Android Views inside a Compose UI -> Option D
  4. Quick Check:

    AndroidView = Embed Views in Compose [OK]
Hint: AndroidView puts Views inside Compose UI [OK]
Common Mistakes:
  • Confusing AndroidView with ComposeView
  • Thinking AndroidView converts Compose to XML
  • Assuming AndroidView replaces Views automatically
2. Which of the following is the correct way to add a Compose UI inside an existing Android View hierarchy?
easy
A. Use AndroidView inside the View XML layout
B. Use ComposeView inside the View hierarchy
C. Replace the View with a Compose function directly
D. Use setContentView with Compose functions

Solution

  1. Step 1: Identify ComposeView usage

    ComposeView is a View that hosts Compose UI inside a traditional View hierarchy.
  2. Step 2: Eliminate wrong options

    Use AndroidView inside the View XML layout is wrong because AndroidView is for Compose to View embedding, not View XML. Replace the View with a Compose function directly is invalid as Views cannot be replaced directly by Compose functions. Use setContentView with Compose functions is for setting Compose as the whole content, not embedding.
  3. Final Answer:

    Use ComposeView inside the View hierarchy -> Option B
  4. Quick Check:

    ComposeView = Compose inside Views [OK]
Hint: ComposeView hosts Compose inside Views [OK]
Common Mistakes:
  • Using AndroidView to embed Compose in Views
  • Trying to replace Views with Compose functions directly
  • Confusing setContentView with embedding Compose
3. What will be displayed when the following Compose code runs?
AndroidView(factory = { context ->
    Button(context).apply {
        text = "Click Me"
    }
})
medium
A. An empty space because Button is not a Compose component
B. A Compose Button with text "Click Me"
C. A traditional Android Button with text "Click Me" inside Compose
D. A runtime error because Button cannot be used inside AndroidView

Solution

  1. Step 1: Analyze AndroidView factory

    The factory creates a traditional Android Button with text "Click Me" inside Compose UI.
  2. Step 2: Understand output

    AndroidView embeds the View, so the Button is shown as a View inside Compose, not a Compose Button.
  3. Final Answer:

    A traditional Android Button with text "Click Me" inside Compose -> Option C
  4. Quick Check:

    AndroidView shows Views inside Compose [OK]
Hint: AndroidView shows Views, not Compose components [OK]
Common Mistakes:
  • Thinking AndroidView creates Compose components
  • Expecting runtime error for Button usage
  • Confusing Android Button with Compose Button
4. Identify the error in this Compose code embedding a View:
AndroidView(factory = { context ->
    TextView(context).apply {
        setText("Hello")
    }
}) {
    text = "World"
}
medium
A. Cannot set text inside the trailing lambda; it should be inside factory
B. TextView does not exist in Android Views
C. Missing import for AndroidView
D. Factory lambda must return null

Solution

  1. Step 1: Check AndroidView usage

    The trailing lambda is for updating the View, but text is not a Compose property; it should be set on the View inside the factory or update block.
  2. Step 2: Identify correct usage

    Setting text outside the factory like this causes error because text is not recognized in that scope.
  3. Final Answer:

    Cannot set text inside the trailing lambda; it should be inside factory -> Option A
  4. Quick Check:

    Set View properties inside factory or update lambda [OK]
Hint: Set View properties inside factory or update lambda [OK]
Common Mistakes:
  • Trying to set View properties directly in trailing lambda
  • Assuming trailing lambda is Compose scope
  • Ignoring factory return value requirements
5. You want to gradually migrate an app from Views to Compose. Which approach correctly mixes Compose and Views for a smooth transition?
hard
A. Use ComposeView to add Compose UI inside existing View layouts and AndroidView to add Views inside Compose screens
B. Rewrite all Views to Compose before running the app
C. Use only AndroidView everywhere to avoid Compose
D. Replace setContentView with Compose functions and remove all Views immediately

Solution

  1. Step 1: Understand gradual migration

    Gradual migration means mixing Compose and Views without rewriting everything at once.
  2. Step 2: Identify correct interop usage

    ComposeView embeds Compose inside Views; AndroidView embeds Views inside Compose. Using both allows smooth transition.
  3. Step 3: Eliminate wrong options

    Rewriting all Views to Compose before running the app, using only AndroidView everywhere to avoid Compose, and replacing setContentView with Compose functions and removing all Views immediately are extreme or incorrect approaches that do not support gradual migration.
  4. Final Answer:

    Use ComposeView to add Compose UI inside existing View layouts and AndroidView to add Views inside Compose screens -> Option A
  5. Quick Check:

    ComposeView + AndroidView = smooth migration [OK]
Hint: Use ComposeView and AndroidView together for migration [OK]
Common Mistakes:
  • Trying to rewrite entire app at once
  • Using only AndroidView or only ComposeView
  • Removing Views before Compose is ready
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard