0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Jetpack Composeでダークモード/ライトモードを切り替える基本方法

Posted at

Jetpack Compose を使ったアプリで、ダークモード対応方法です。
基本の切り替え方法をシンプルにまとめました。

システムのダークモード/ライトモード状態を取得

Jetpack Compose には、現在のシステムがダークモードかどうかを判定する関数があります。

val isDark = isSystemInDarkTheme()

ライトテーマとダークテーマのカラースキームをMaterialThemeで切り替え

private val LightColorScheme = lightColorScheme(
    primary = Color(0xFF6200EE),
    background = Color.White,
    onBackground = Color.Black
)

private val DarkColorScheme = darkColorScheme(
    primary = Color(0xFFBB86FC),
    background = Color.Black,
    onBackground = Color.White
)

@Composable
fun MyAppTheme(
    useDarkTheme: Boolean = isSystemInDarkTheme(),
    content: @Composable () -> Unit
) {
    val colors = if (useDarkTheme) DarkColorScheme else LightColorScheme

    MaterialTheme(
        colorScheme = colors,
        typography = Typography,
        content = content
    )
}

MainScreenのサンプルコード

@Composable
fun MainScreen() {
    // MaterialTheme の色を使って背景とテキスト色を取得
    val backgroundColor = MaterialTheme.colorScheme.background
    val textColor = MaterialTheme.colorScheme.onBackground

    Surface(
        modifier = Modifier
            .fillMaxSize()
            .background(backgroundColor),
        color = backgroundColor
    ) {
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = "Hello, Jetpack Compose!",
                color = textColor,
                style = MaterialTheme.typography.headlineMedium
            )
        }
    }
}

実行結果

ライトモード ダークモード
スクリーンショット 2025-06-22 18.53.41.png スクリーンショット 2025-06-22 18.52.42.png
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?