Android Compose 튜토리얼 | Android 개발자 | Android Developers
Jetpack Compose는 네이티브 Android UI를 빌드하기 위한 최신 도구 키트입니다. Jetpack Compose는 더 적은 수의 코드, 강력한 도구, 직관적인 Kotlin API로 Android에서의 UI 개발을 간소화하고 가속화합니다. 이
developer.android.com
Lesson 2: Layouts
UI 요소는 계층이 있으며, 다른 요소를 포함 가능
Compose는 Composable function 안에서 다른 Composable function을 호출하여 UI 계층 생성 가능
Add multiple texts
한 Composable function은 여러 개의 Composable function 호출 가능
// ...
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MessageCard(Message("Android", "Jetpack Compose"))
}
}
}
data class Message(val author: String, val body: String)
@Composable
fun MessageCard(msg: Message) {
Text(text = msg.author)
Text(text = msg.body)
}
@Pre@Preview
@Composable
fun PreviewMessageCard() {
val msg = Message("Colleague", "Hey, take a look at Jetpack Compose, it's great!")
MessageCard(message = msg)
}
Using a Column
Column function로 요소들을 수직으로 배열 가능
// ...
import androidx.compose.foundation.layout.Column
@Composable
fun MessageCard(msg: Message) {
Column {
Text(text = msg.author)
Text(text = msg.body)
}
}
Row를 통해 수평으로 아이템 배열 가능
Box를 가지고 요소를 쌓을 수 있음
Add an image element
Image composable로 이미지 삽입 가능
// ...
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Row
import androidx.compose.ui.res.painterResource
@Composable
fun MessageCard(msg: Message) {
Row {
Image(
painter = painterResource(R.drawable.profile_picture),
contentDescription = "Contact profile picture",
)
Column {
Text(text = msg.author)
Text(text = msg.body)
}
}
}
+ Resource Manager로 사진 갤러리에서 이미지를 가져올 수 있음
Configure your layout
Modifiers는 Composable을 꾸미고 설정하는 데 사용
Composable의 크기, 레이아웃, 모양 변경하거나, 상위 수준의 인터렉션(요소 클릭 등) 추가 가능
체인을 사용해 더 복잡한 Composable 생성 가능
// ...
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
@Composable
fun MessageCard(msg: Message) {
// Add padding around our message
Row(modifier = Modifier.padding(all = 8.dp)) {
Image(
painter = painterResource(R.drawable.profile_picture),
contentDescription = "Contact profile picture",
modifier = Modifier
// Set image size to 40 dp
.size(40.dp)
// Clip image to be shaped as a circle
.clip(CircleShape)
)
// Add a horizontal space between the image and the column
Spacer(modifier = Modifier.width(8.dp))
Column {
Text(text = msg.author)
// Add a vertical space between the author and message texts
Spacer(modifier = Modifier.height(4.dp))
Text(text = msg.body)
}
}
}