Compose Styles API
목차
지난 Google I/O의 What’s new in Android 세션에서 Styles API에 대한 발표가 인상적이었어서, 이번 글에서는 Compose Styles API에 대해 정리해보고자 합니다.
위 발표 영상에서도 Styles API를 잘 설명해주지만, 공식 문서에서 제게 눈에 띄었던 부분을 간단하게 소개해보고 싶습니다.
참고로 Styles API는 아직
ExperimentalFoundationStyleApi가 붙어 있는 실험적 API입니다!!!
우리 앱만의 Button을 만들다 보면
서비스를 개발하다 보면 거의 반드시 이런 시도를 하게 됩니다.
우리 앱만의 버튼 컴포넌트를 만들자. 또는 우리 앱만의 디자인 시스템을 적용한 컴포넌트를 만들자.
처음에 디자인은 신경 쓰지 않고 기능만 생각하면 아주 단순합니다.
@Composablefun CustomButton( text: String, onClick: () -> Unit) { Button(onClick = onClick) { Text(text) }}하지만 이제 우리 앱만의 버튼, 즉 아래 요구사항을 반영하려다 보면 이야기가 달라집니다.
- 기본 배경색
- disabled 상태 배경색
- pressed 상태 색
- hover 상태 색
- shape
- border
- text style
- padding
- loading 상태
그러다 어느 순간 버튼 컴포넌트가 이런 모양이 됩니다.
CustomButton( backgroundColor = BrandColor.Primary, disabledBackgroundColor = BrandColor.DisabledContainer, shape = RoundedCornerShape(12.dp), textStyle = AppTypography.buttonLarge, border = BorderStroke(1.dp, BrandColor.PrimaryDark), pressedColor = BrandColor.PrimaryPressed, hoveredColor = BrandColor.PrimaryHover)처음에는 필요한 파라미터를 하나씩 추가했을 뿐인데, 어느새 컴포넌트가 시각적 파라미터로 가득 차게 됩니다.
Modifier만으로는 부족한 순간
Compose에서는 많은 UI 속성을 Modifier로 설정할 수 있습니다.
Modifier .background(Color.Blue) .padding(16.dp) .clickable { }배경, 패딩, 클릭 영역처럼 UI 노드에 붙는 속성은 Modifier가 잘 처리합니다.
하지만 모든 스타일이 Modifier에 있는 것은 아닙니다.
예를 들어 텍스트 스타일은 보통 Text의 파라미터로 들어갑니다.
Text( text = "Login", style = AppTypography.buttonLarge)disabled 상태 색상은 컴포넌트 내부에서 직접 분기하거나, Material 컴포넌트라면 ButtonDefaults.buttonColors() 같은 API를 사용합니다.
val containerColor = if (enabled) BrandColor.Primary else BrandColor.DisabledContainer즉 하나의 버튼 외형을 만들기 위해 필요한 값들이 여러 위치로 흩어지게 됩니다.
- 배경, 패딩, 클릭 영역은
Modifier - 텍스트 스타일은
TextStyle - disabled 처리는 컴포넌트 상태
- pressed, hovered, focused는 interaction 상태
- 앱 전체 색상과 shape는 theme
이 구조는 작고 독립적인 컴포넌트 조각을 조합하여 하나의 화면을 만들고자하는 선언형 UI(Compose)의 composability 관점에서는 합리적입니다만…. 우리 서비스만의 디자인 시스템 컴포넌트를 만드는 입장에서는 계속해서 파라미터가 늘어나는 단점이 분명하게 존재합니다.
그렇다면 Styles API를 적용하면 어떻게 바뀔까요??
Style 객체로 커스텀 버튼 만들기
먼저 스타일 객체를 선언합니다.
val primaryButtonStyle = Style { background(BrandColor.Primary) shape(RoundedCornerShape(12.dp)) textStyle(AppTypography.buttonLarge) border(1.dp, BrandColor.PrimaryDark) contentPadding(horizontal = 16.dp, vertical = 10.dp)
disabled { background(BrandColor.DisabledContainer) }
pressed { background(BrandColor.PrimaryPressed) }
hovered { background(BrandColor.PrimaryHover) }}그리고 우리 앱만의 버튼에는 style 파라미터로 넣어주기만 하면 됩니다.
CustomButton( style = primaryButtonStyle)기존 코드와 비교해보면 차이가 꽤 명확합니다.
CustomButton( backgroundColor = BrandColor.Primary, disabledBackgroundColor = BrandColor.DisabledContainer, shape = RoundedCornerShape(12.dp), textStyle = AppTypography.buttonLarge, border = BorderStroke(1.dp, BrandColor.PrimaryDark), pressedColor = BrandColor.PrimaryPressed, hoveredColor = BrandColor.PrimaryHover)이렇게 늘어나던 시각적 파라미터를 하나의 Style로 넘길 수 있게 됩니다.
오케이! 파라미터 개수가 확 줄어서 쓰기도 편하고 관리하기도 쉬워 보입니다.
그거 말고는 없을까요?
상태별 외형을 한 곳에서 관리하기
앞선 예시에도 살짝 나왔지만, Styles API가 매력적인 부분은 상태별 디자인을 한 번에 관리할 수 있다는 점입니다.
Style { background(Color.Blue)
pressed { background(Color.DarkBlue) }
disabled { background(Color.Gray) }
hovered { background(Color.Cyan) }}기존에는 enabled 상태, pressed 상태, hover 상태를 컴포넌트 내부에서 따로 처리해야 했습니다.
val backgroundColor = when { !enabled -> BrandColor.DisabledContainer isPressed -> BrandColor.PrimaryPressed isHovered -> BrandColor.PrimaryHover else -> BrandColor.Primary}물론 이런 방식도 가능합니다. 하지만 상태가 늘어날수록 컴포넌트 내부 구현이 점점 복잡해집니다.
Styles API는 이런 상태별 시각 표현을 Style 안에 모읍니다.
val primaryButtonStyle = Style { background(BrandColor.Primary)
disabled { background(BrandColor.DisabledContainer) }
pressed { background(BrandColor.PrimaryPressed) }
hovered { background(BrandColor.PrimaryHover) }}| 개념 | 의미 |
|---|---|
click |
눌렀다가 뗀 뒤 실행되는 이벤트 |
pressed |
누르고 있는 중인 상태 |
hovered |
마우스/포인터가 위에 올라와 있는 상태 |
disabled |
컴포넌트가 비활성화된 상태 |
이런 상태를 스타일 안에서 선언적으로 표현할 수 있다는 점이 Styles API의 중요한 특징입니다.
스타일 합성하기
디자인 시스템을 만들다 보면 기본 버튼 스타일 위에 특정 화면만의 스타일을 조금 덧씌우고 싶을 때가 많습니다.
예를 들어 기본 버튼 스타일은 파란색인데, 삭제 버튼에서는 배경색만 빨간색으로 바꾸고 싶을 수 있습니다.
Styles API에서는 then으로 스타일을 합성할 수 있습니다.
val baseStyle = Style { background(Color.Blue) contentPadding(16.dp)}
val dangerStyle = Style { background(Color.Red)}
val result = baseStyle then dangerStyle이 경우 뒤에 붙은 dangerStyle이 같은 속성을 덮어씁니다.
최종 결과는 다음과 비슷합니다.
Style { background(Color.Red) contentPadding(16.dp)}약간 설명이 부족할 수 있어서 예를 들어보자면 완전히 같진 않지만 CSS에서의 문법과 매우 유사합니다. 저는 이거 처음보고 어 이거 CSS 아닌가? 싶었는데 유튜브 댓글 반응도 Android용 CSS라는 반응이 보이더라구요.
.button { background: blue; padding: 16px;}
.button.danger { background: red;}최종적으로는 background는 red가 되고, padding은 유지됩니다.
CustomButton 내부는 어떻게 생겼을까
그렇다면 CustomButton(style = primaryButtonStyle)은 내부에서 어떻게 이 스타일을 적용할까요?
핵심은 Modifier.styleable(...)입니다.
디자인 시스템 컴포넌트는 기본 스타일을 내부에 가지고 있고, 외부에서는 필요한 경우 style 파라미터로 일부 시각적 속성만 덮어쓸 수 있습니다.
먼저 우리 앱 버튼의 기본 스타일을 정의합니다.
object AppButtonDefaults { val primaryStyle = Style { background(BrandColor.Primary) shape(RoundedCornerShape(12.dp)) textStyle(AppTypography.buttonLarge) contentPadding(horizontal = 16.dp, vertical = 10.dp)
disabled { background(BrandColor.DisabledContainer) }
pressed { background(BrandColor.PrimaryPressed) } }}그리고 CustomButton은 modifier 뒤에 style 파라미터를 받습니다.
@OptIn(ExperimentalFoundationStyleApi::class)@Composablefun CustomButton( onClick: () -> Unit, modifier: Modifier = Modifier, style: Style = Style, enabled: Boolean = true, content: @Composable RowScope.() -> Unit,) { val interactionSource = remember { MutableInteractionSource() }
val styleState = rememberUpdatedStyleState(interactionSource) { it.isEnabled = enabled }
Row( modifier = modifier .clickable( enabled = enabled, onClick = onClick, interactionSource = interactionSource, indication = null, ) .styleable( styleState, AppButtonDefaults.primaryStyle, style ), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, content = content, )}여기서 중요한 부분은 이 코드입니다.
.styleable( styleState, AppButtonDefaults.primaryStyle, style)AppButtonDefaults.primaryStyle은 디자인 시스템의 기본버튼 스타일이고, style은 호출부에서 전달받은 추가 스타일입니다.
즉 기본 버튼은 이렇게 사용할 수 있습니다.
CustomButton( onClick = { }) { Text("확인")}특정 화면에서 배경색만 바꾸고 싶다면 이런식으로 삭제 버튼을 만들 수 있습니다.
val dangerButtonStyle = Style { background(BrandColor.Danger)
pressed { background(BrandColor.DangerPressed) }}CustomButton( onClick = { }, style = dangerButtonStyle) { Text("삭제")}이 경우 버튼은 기본적으로 AppButtonDefaults.primaryStyle을 따르지만, dangerButtonStyle이 같은 속성을 덮어씁니다.
결과적으로 기본 shape, textStyle, contentPadding은 유지하면서 background와 pressed 상태의 배경만 바꿀 수 있습니다.
이 구조에서 역할은 나뉩니다.
- 클릭 처리, gesture 같은 동작은
Modifier와 컴포넌트 로직이 담당합니다. - 배경색, shape, padding, 상태별 외형 같은 시각적 규칙은
Style이 담당합니다.
즉 CustomButton은 동작과 구조를 유지하면서, 외형만 Style을 통해 유연하게 바꿀 수 있게 됩니다.
디자인 시스템 관점에서의 장점
Styles API를 디자인 시스템 관점에서 보면 장점을 정리해보겠습니다.
첫 번째, 컴포넌트 파라미터가 줄어듭니다.
CustomButton( style = primaryButtonStyle)두 번째, 상태별 외형을 한 곳에서 관리할 수 있습니다.
Style { background(BrandColor.Primary)
pressed { background(BrandColor.PrimaryPressed) }
disabled { background(BrandColor.DisabledContainer) }}세 번째, 기본 스타일과 화면별 스타일을 합성할 수 있습니다.
val result = baseButtonStyle then screenSpecificStyle네 번째, 테마와 연결하기 좋습니다.
val buttonStyle = Style { background(colors.brand) shape(shapes.medium) textStyle(typography.labelLarge)}결국 Styles API는 “컴포넌트를 어떻게 그릴지”에 대한 시각적 규칙을 컴포넌트 파라미터가 아니라 Style 객체로 분리하려는 시도라고 볼 수 있습니다.
주의할 점
아직 Styles API는 실험적입니다.
공식 문서에서도 Styles API는 @Experimental이며 변경될 가능성이 있다고 안내하고 있습니다. 또 Material 컴포넌트에서의 정식 지원 계획도 아직 정해진 바가 없습니다.
따라서 지금 당장 도입해야한다? 이런 관점이 아니라, Compose가 디자인 시스템 컴포넌트 문제를 이런 방향으로 해결하려하는구나 이 방향성을 느끼는 것만으로 의미있다고 생각합니다.
또한 hovered 상태는 환경에 따라 확인하기 어려울 수 있습니다. 실제 터치 기기에서는 hover가 없고, Android Studio Preview나 에뮬레이터에서도 마우스 hover를 해도 이벤트가 발생하지 않더라구요…
마무리

유튜브 영상에서 새로 나온 Sytles API로 인해 Modifier를 Deprecated 되었다라는 썸네일로 관심을 끄는 영상도 등장하고 있는데요.
공식문서에서도 이걸 분명하게 부정하고 있고, 위의 글들의 내용을 보아도 사실이 아님을 아실 수 있습니다.
Modifier는 “어떻게 배치되고 동작할지” 그리고 Style은 “어떻게 보일지”에 목적을 두는 것입니다.
아직 실험적인 API지만, 컴포즈의 방향성을 체감하는 흥미로운 주제였던 것 같습니다.
추가로 퍼포먼스에 대해서도 장점이 있다는 내용이 있었지만 이 부분은 추가로 공부가 필요할 것 같아 추후에 기회가 되면 보충해서 포스팅해보겠습니다. 감사합니다.
댓글
댓글은 GitHub 계정으로 작성하며 GitHub Discussions에 저장됩니다.