0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Jetpack Compose】Previewで実行されているかを判定する

Posted at

ComposeでPreviewで実行されているかをコードで判定する

結論、以下のコードでComposable関数がPreviewで実行中かを判定することができます。

import androidx.compose.ui.tooling.PreviewActivity

val isInPreview: Boolean
  @Composable
  get() = LocalInspectionMode.current || LocalLifecycleOwner.current is PreviewActivity
API 説明
LocalInspectionMode.current Android StudioのCompose Preview上でComposable関数のPreviewが実行されているかどうか。trueでPreview上で実行中。
(実機やエミュレータ上で実行中の場合だとfalse)

LocalInspectionMode.currentだけをみて判定すると実機やエミュレータでPreviewを実行した時に判定できなくなってしまいます。
そこで実機やエミュレータではcompose.ui.tooling.PreviewActivityというActivityの上で実行されるという仕組みを利用してPreviewかどうかを判定することができます。
(Composeのアップデートによって将来的に変更される可能性もあります。本記事はCompose v1.4系の情報です。)

無闇にPreviewかどうかを判定するコードをComposable関数に入れるのはやめた方が良いですが、
稀に本当に稀にPreviewの時だけ何かをやりたい、やらせたくないなどのケースがあるので知っておくと役に立つ時が来るかもしれないです。

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?