Previewing Composables

If you are a fan of Android Studio’s design view for XML layouts, you may be wondering if you can preview your Compose layouts the same way. Preview functionality is available for Compose, but Android Studio needs a little help: You must opt in to previews for each composable. Do this now for your ToppingCell composable by annotating it with the @Preview annotation.

Listing 26.9  Enabling previews on a composable (ToppingCell.kt)

@Preview
@Composable
fun ToppingCell() {
    ...
}

Android Studio uses your project’s compiled code to generate previews of composables. This means that your project must be built to show changes you have made in the preview. Build your project now by pressing the Enabling previews on a composable (ToppingCell.kt) Build icon in Android Studio’s toolbar.

When the build finishes, click the Split tab with ToppingCell.kt open in the editor. You should see the preview in the right side of the editor (Figure 26.5). (If you do not, check that your project has built successfully, with no errors.)

Figure 26.5  Previewing a composable

Previewing a composable

As you saw with XML layouts, the preview matches what the user will see when your composable is placed onscreen. Remember that Android Studio needs to recompile your code before it can update the preview, so your changes will not appear instantly the way they did with XML layouts.

The @Preview annotation has one very noteworthy limitation: By default, it is not able to show previews for composables that have parameters (unless each parameter has a default value). When this happens, you need to specify the values to use for those arguments. There is a mechanism for doing this with the @Preview annotation, but we find it to be cumbersome to set up. Instead, many developers create a separate preview function. This dedicated preview function can pass the desired inputs to the composable being previewed while specifying no inputs of its own.

In just a moment, you are going to add parameters to your ToppingCell composable. To avoid breaking its preview, preemptively add a separate preview function in the same file:

Listing 26.10  A dedicated preview composable (ToppingCell.kt)

@Preview
@Composable
private fun ToppingCellPreview() {
    ToppingCell()
}

@Preview
@Composable
fun ToppingCell() {
    ...
}

This preview composable uses the private visibility modifier, allowing you to define the preview without exposing it for use in your production code. Refresh the preview by rebuilding the project or by clicking the A dedicated preview composable (ToppingCell.kt) Build Refresh button in the preview window. The preview should look identical except for being labeled ToppingCellPreview instead of ToppingCell.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset