
Jetpack Compose는 Modifier라는 인터페이스를 제공합니다. modifier를 이용하면 Composable function의 동작이나 모양을 변경할 수 있습니다.
위에서 설명한 것처럼 Modifier는 Composable 요소의 표면적이나 배치, 그리고 다른 여러가지 기능을 변경할 수 있도록 도와주는 인터페이스 입니다. 기본적으로는 아무런 효과가 없는 빈 상태이지만 리를 조합하여 다양한 기능을 추가할 수 있습니다.
Text(
text = "Hello, Compose!",
modifier = Modifier
.padding(16.dp)
.background(Color.Blue)
)
다음과 같이 사용을 한다면 Text Composable 요소는 Modifier를 통해 16dp의 패딩과 파란 배경을 가지게 됩니다.
사용시 주의(?)사항
1. Modifier.padding(16.dp).background(Color.Blue)
2. Modifier.background(Color.Blue).padding(16.dp)
1번과 2번 코드는 다른 결과를 가져옵니다.
첫 번째의 경우에는 패딩이 적용된 후 파란색 배경이 적용되며, 두 번째는 파란 배경이 적용된 후 패딩이 적용됩니다.
infix fun then(other: Modifier): Modifier =
if(other === Modifier) this else CombinedModifier(this, other)
Modifier를 인자로 넘겨주면 해당 Modifier를 연결한 새로운 Modifier가 반환됩니다. then을 활용하면 Custom이 가능한데 다음과 같이 사용할 수 있습니다. 실제로 제공되고 있는 padding의 경우에도 then을 통해 구현했습니다.
fun Modifier.padding(
start: Dp = 0.dp,
top: Dp = 0.dp,
end: Dp = 0.dp,
bottom: Dp = 0.dp
) = this.then(
PaddingModifier(
start = start,
top = top,
end = end,
bottom = bottom,
rtlAware = true,
inspectorInfo = debugInspectorInfo {
name = "padding"
properties["start"] = start
properties["top"] = top
properties["end"] = end
properties["bottom"] = bottom
}
)
)
그 외의 Tip??
drawBehind
drawBehind는 Composable 함수 뒤에 무언가를 그릴 때 사용됩니다.
drawWithContent
모양/내용 위에 모양을 그릴 때 사용할 수 있습니다.
drawWithCache
drawWithCache 수정자는 도면 영역이 변경될 때까지 객체를 캐시하는데 사용됩니다. 무언가를 렌더링하기 위해 무거운 계산을 할 때 사용하는 것이 좋습니다.