12

I started using Jetpack Compose and I'm very happy with it. I replaced a couple of layouts that where defined in xml by a @Composable function.

When I went back to my Navigation-xml I noticed that the preview inside every screen is done with tools:layout property. And property reference to a layout in xml. Not to an @Composable function.

Is there already a way to reference to a @Composable function from tools:layout in a Navigation xml so that the preview of my entire flow will be visible?

2
  • 3
    Navigation does not support Compose. When it does, I expect that it will be via the Kotlin DSL, not the XML navigation resource. Commented Sep 11, 2020 at 10:57
  • seems like this is still unavoidable because even google sample github.com/android/sunflower still has the same issue in class tools:layout="@layout/fragment_plant_detail"> which is @composable and there is no solution yet. Commented Oct 27, 2022 at 22:28

1 Answer 1

0

Jetpack Compose uses Navigation Compose, which replaces XML navigation graphs with a Kotlin DSL.

  1. Add the dependency (if not already present)
implementation "androidx.navigation:navigation-compose:2.7.6"
  1. Replace XML navigation with Compose navigation
@Composable
fun MyApp() {
    val navController = rememberNavController()
    NavHost(navController, startDestination = "home") {
        composable("home") { HomeScreen() }
        composable("details") { DetailsScreen() }
    }
}

@Composable
fun HomeScreen() {
    // Your Compose UI here
    Text("Home")
}


@Preview
@Composable
fun HomeScreenPreview() {
    HomeScreen()
}

.

Migration tip: If you were using <fragment> in XML, switch entirely to NavHost + composable in Compose. The two systems (XML navigation + Compose) don't interoperate for previews. Stick to Navigation Compose's Kotlin-first approach.

New contributor
cipher010 is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.