/ kyokomi note / blog

JetpackComposeで作った個人アプリをMaterial3に対応

August 13, 2022 [Android]

JetpackComposeで作った個人アプリをMaterial3に対応したので、そのメモ。

環境

導入手順

app/gradle.ktsの修正

// app/build.gradle.kts
dependencies {
	... 
	
	implementation("androidx.compose.material3:material3:1.0.0-alpha14")
	implementation("androidx.compose.material3:material3-window-size-class:1.0.0-alpha14")
}

versionCatalogを使ってる場合はこんな感じ

// libs
[versions]

...

androidx-material3 = "1.0.0-alpha14"

[libraries]

...

androidx-compose-material3 = { module = "androidx.compose.material3:material3", version.ref = "androidx-material3" }
androidx-compose-material3-window-size = { module = "androidx.compose.material3:material3-window-size-class", version.ref = "androidx-material3" }
// app/build.gradle.kts
dependencies {
	... 
	
	implementation(libs.androidx.compose.material3)
	implementation(libs.androidx.compose.material3.window.size)
}

Material 2 -> 3 migration

基本的にはmigrationのガイドがあるのでこれを見て対応していけばOK https://material.io/blog/migrating-material-3

参考までに自分が対応したものが以下。

composeのimport修正

Fontの修正

colorの修正

Material-Theme-Builder(Figma)が便利 https://www.figma.com/file/s9f3Mr8X6ZB1ZAUbykdXr1/Material-Theme-Builder-(Community)?node-id=0%3A1

Image from Gyazo

TopAppBarの修正

Dynamic Color対応

端末側で設定したカラーを使いたい場合の実装。

// Theme.kt
package dev.kyokomi.xxxxx.ui.theme

import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext

@Composable
fun MyMaterialTheme(
    darkTheme: Boolean = isSystemInDarkTheme(),
    content: @Composable () -> Unit,
) {
    // https://developer.android.com/jetpack/compose/themes/material#m3-colorscheme
    // Dynamic color is available on Android 12+
    val dynamicColor = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
    val colorScheme = when {
        dynamicColor && darkTheme -> dynamicDarkColorScheme(LocalContext.current)
        dynamicColor && !darkTheme -> dynamicLightColorScheme(LocalContext.current)
        darkTheme -> darkColorScheme()
        else -> lightColorScheme()
    }

    MaterialTheme(
        colorScheme = colorScheme,
        typography = MaterialTheme.typography,
        content = content,
    )
}

動いた

参考

last modified August 13, 2022

👋 Related posts in the Android series...