AppThemeの設定について
from Android開発
構造
code:text
app/src/main/java/com.example.app/ui/
├ ...
├ theme/
| ├ AppSemanticColors.kt
| ├ ButtonTheme.kt
| ├ Color.kt
| ├ Effect.kt
| ├ FontProvider.kt
| └ Theme.kt
└ MainActivity.kt
MainActivityについて
MainActivity の役割は、Android の起動入口として setContent を呼び、Compose UI ツリーを開始すること。その後、AppTheme { ... } の中でアプリ全体のデザインルールを適用し、その内側に実際の画面、例えば HomeScreen や LoginScreen、AppNavHost などが入る。
code:MainActivity.kt
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
AppTheme{
MainNavigation()
}
}
}
}
Theme.kt
アプリ全体のテーマを定義する。
code:Theme.kt
@Composable
fun AppTheme(
content: @Composable () -> Unit
) {
val colors = appSemanticColors()
val typography = appTypography()
CompositionLocalProvider(
LocalAppSemanticColors provides colors
) {
MaterialTheme(
colorScheme = colorScheme,
typography = typography,
content = content
)
}
}
Color.kt
アプリで使う色を定義する。
code:Color.kt
val Blue500 = Color(0xFF2196F3)
val Gray900 = Color(0xFF212121)
val White = Color(0xFFFFFFFF)
AppSemanticColors.kt
意味を持った色を定義する。
code:AppSemanticColors.kt
val LightSemanticColors = AppSemanticColors(
background = White,
primaryText = Gray900,
secondaryText = Gray600,
error = Red500,
success = Green500,
buttonPrimaryBackground = Blue500,
buttonPrimaryText = White
)
// Composable関数内での使い方
Text(
text = "ログイン",
color = AppTheme.colors.primaryText
)
ButtonTheme.kt
code:ButtonTheme.kt
// 組み立て用ボタンスクリプト ui/component/Buttonから呼び出される
// ボタンのスタイルクラス
@Composable
fun buttonStyle(isPressed: Boolean): ButtonStyle {
return ButtonStyle(colors = buttonColors(isPressed))
}
// ボタンスタイルの定義
data class ButtonStyle(
val colors: ButtonColors,
val borderColors: ButtonBorderColors? = null
)
// ボタンの色を返す
@Composable
fun buttonColors(isPressed: Boolean): ButtonColors {
return when {
isPressed -> {
ButtonDefaults.buttonColors(
containerColor = semanticColors.colorBrandBlue800,
contentColor = semanticColors.colorTextOnBrand,
disabledContainerColor = semanticColors.colorSurfaceDisabled,
disabledContentColor = semanticColors.colorTextDisabled
)
}
else -> {
ButtonDefaults.buttonColors(
containerColor = semanticColors.colorBrandBlue600,
contentColor = semanticColors.colorTextOnBrand,
disabledContainerColor = semanticColors.colorSurfaceDisabled,
disabledContentColor = semanticColors.colorTextDisabled
)
}
}
}
code:Button.kt
@Composable
fun DefaultButton(
text: String,
modifier: Modifier = Modifier,
enabled: Boolean = true,
textStyle: TextStyle = semanticTypography.calloutBold,
iconResource: Int? = null,
onClick: () -> Unit,
){
val interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }
val isPressed by interactionSource.collectIsPressedAsState()
Button(
modifier = modifier
.defaultMinSize(minHeight = 32.dp)
.fillMaxWidth(),
onClick = onClick,
enabled = enabled,
interactionSource = interactionSource,
){
Text(
text = text,
style = textStyle
)
}
}