LoginSignup
0
0

More than 1 year has passed since last update.

Compose Multipreview Annotationsで複数のバリエーションのPreviewを表示させる

Last updated at Posted at 2022-05-18

Jetpack Compose 1.2 と Android Studio Dolphin 以降の組み合わせで Compose Multipreview Annotations の仕組みを使い、複数の @Preview を一つの Annotation で表現することができます。

実装

これまで、例えば Light Theme と Dark Theme の Compose のプレビューを表示したい場合は、以下のように複数の @Preview を使って実装していました。

@Preview
@Preview(
    uiMode = Configuration.UI_MODE_NIGHT_YES
)
@Composable
fun PreviewMilestoneItem() {
    MilestoneItem()
}

これが Compose Multipreview Annotations を使って複数の @Preview をまとめることができます。
上の例をまとめるとこのようになります。

@Preview(
    name = "Light theme",
    group = "Themes",
)
@Preview(
    name = "Dark theme",
    group = "Themes",
    uiMode = Configuration.UI_MODE_NIGHT_YES
)
annotation class ThemePreviews

// usage
@ThemePreviews
@Composable
fun PreviewMilestoneItem() {
    MilestoneItem()
}

ユースケース

まとめた Annotation を他の Preview で使いまわせるので、プロジェクトで一つ用意しておけばあらゆるところで共通の Preview の設定にすることができます。
また、まとめた Annotation を複数同時に指定したり、まとめた Annotation に別のまとめた Annotation をつけることもできます。

@Preview(
    name = "Small font",
    group = "Font",
    fontScale = 0.5f
)
@Preview(
    name = "Normal font",
    group = "Font",
    fontScale = 1.0f
)
annotation class FontScalePreviews

@Preview(
    name = "Pixel 4",
    group = "Device",
    device = Devices.PIXEL_4,
    showSystemUi = true
)
@Preview(
    name = "Foldable",
    group = "Device",
    device = Devices.FOLDABLE,
    showSystemUi = true
)
annotation class DevicePreviews


@Preview(
    name = "Light theme",
    group = "Theme",
)
@Preview(
    name = "Dark theme",
    group = "Theme",
    uiMode = Configuration.UI_MODE_NIGHT_YES
)
annotation class ThemePreviews

// usage
@FontScalePreviews
@DevicePreviews
@ThemePreviews
@Composable
fun PreviewMilestoneItem() {
    MilestoneItem()
}

or

@FontScalePreviews
@DevicePreviews
@ThemePreviews
annotation class CompletePreviews

@CompletePreviews
@Composable
fun PreviewMilestoneItem() {
    MilestoneItem()
}

@Previewgroup を指定しておくことで、プレビューから指定した group だけの表示も可能になります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0