반응형
1. 예제
(1) TwoWeekSecondEx1
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val onClick : () -> Unit = {}
PrimaryButton(enabled = true, text = "확인", onClick = onClick)
}
}
}
//실습 1
@Composable
fun PrimaryButton(
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean,
text: String
) {
Button(
onClick = onClick,
modifier = modifier
.fillMaxWidth()
.height(52.dp)
.clickable { },
enabled = enabled,
shape = RoundedCornerShape(12.dp),
colors = ButtonDefaults.buttonColors(
containerColor = Blue500,
disabledContainerColor = Gray100
)
) {
Text(
text = text,
color = if (enabled) Color.White else Gray150,
fontWeight = FontWeight.Bold
)
}
}
@Preview(
showBackground = true,
name = "enabled")
@Composable
fun PrimaryButtonPreview(){
val onClick : () -> Unit = {}
PrimaryButton(enabled = true, text = "확인", onClick = onClick )
}
@Preview(
showBackground = true,
name = "disabled")
@Composable
fun PrimaryButtonDisablePreview(){
val onClick : () -> Unit = {}
PrimaryButton(enabled = false, text = "확인", onClick = onClick )
}
버튼 클릭시 회색으로 변하는 구조이다. 컴포즈는 xml이 메서드화 되어 있는 것으로 코드와 메서드화 되어 있는 뷰를 같이 유연성있게 사용할 수 있어 유용하다. 특히 버튼, 채팅말풍선, 텍스트상자와 같이 반복적으로 사용되는 뷰를 코드와 같이 혼합하여 사용하여 코드의 양을 줄이고 코드와 뷰를 같이 보고 수정할 수 있는 장점이 있다. Button 구조에 대해 자세하게 작성되어 버튼 구현에 있어 좋은 예제가 될 것 같다.
(2) TwoWeekSecondEx2
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
}
}
}
// 2주차 두번째 수업 실습2
@Composable
fun ProductDetailScreen() {
Column(
modifier = Modifier
.background(Color.White)
.fillMaxSize()
.verticalScroll(rememberScrollState())
) {
Image(
painter = painterResource(id = R.drawable.ic_launcher_background),
contentDescription = stringResource(R.string.app_name),
modifier = Modifier.fillMaxWidth(),
contentScale = ContentScale.Crop
)
Spacer(Modifier.height(24.dp))
val horizontalPadding = Modifier.padding(horizontal = 16.dp)
Text(
text = "twg. official",
modifier = horizontalPadding
)
Spacer(Modifier.height(16.dp))
Row {
Text(
text = "[19차 리오더] 페이크 레더 숏 테일러 자켓 블랙(1 color)",
modifier = horizontalPadding.then(
Modifier
.weight(1f)
.align(Alignment.CenterVertically)
)
)
Icon(
imageVector = Icons.Default.Favorite,
contentDescription = "Add Favorite",
modifier = Modifier
.align(Alignment.CenterVertically)
.padding(16.dp)
)
}
Spacer(Modifier.height(24.dp))
Row(modifier = horizontalPadding) {
Text(
text = "정상가"
)
Text(
text = "99,800원",
modifier = Modifier.padding(start = 8.dp)
)
}
Spacer(Modifier.height(24.dp))
Divider()
Text(
text = "상품 설명",
modifier = Modifier.padding(16.dp)
)
Image(
painter = painterResource(id = R.drawable.ic_launcher_background),
contentDescription = "상품 상세 이미지",
modifier = Modifier.fillMaxWidth(),
contentScale = ContentScale.Crop
)
}
}
//Recomposition
@Composable
fun CounterButton() {
var count by remember { mutableStateOf(0) }
ClickCounter(clicks = count) {
count += 1
}
}
@Composable
fun ClickCounter(clicks: Int, onClick: () -> Unit) {
Column {
Text(text = "Recomposition Test")
Button(onClick = onClick) {
Text("I've been clicked $clicks times")
}
}
}
@Composable
@Preview
fun ProductDetailScressnPreview(){
ProductDetailScreen()
}
@Composable
@Preview
fun CounterButtonPreview(){
CounterButton()
}
컴포즈로 쇼핑몰 페이지를 제작하였다. 쇼핑몰페이지와 같은 구조를 사용할때는 xml구조와 큰 차이가 없다. 하지만 내부에 사용되는 반복되는 뷰작업에 대해서는 이점이 많다. (ex 버튼, 텍스트상자, 상품설명란 등..) 전체적인 Compose 뷰 구성을 한번에 제작해 Spacer와 Divider(가로줄), Image, Row를 사전에 생각하고 구성해본 좋은 예제이다.
Compose는 어떻게 보면 뷰를 하나의 객체로서 생각하고 구현하면 쉽게 생각할 수 있는 것 같다. 각각의 객체들을 모아 하나의 뷰를 완성하고 용도에 따라 반복적으로 사용하거나 용도에 따라 변경하여 사용할 수도 있다. 이것을 선언형이라고 하는데 기존 xml 방식은 명령형인데 반해 Compose는 선언형으로 state 값을 변경하면 변경된 View를 보여준다. 마치 하나의 메서드처럼 동작한다. 다음번 Compose는 MVVM과 비동기를 같이 활용하여 심도 있는 프로젝트를 진행해 볼 까 한다.
반응형
'Android > Android Kotlin' 카테고리의 다른 글
[Android Kotlin] Scaffold (0) | 2024.08.02 |
---|---|
[Android Kotlin] LazyColumn (0) | 2024.08.02 |
[Android Kotlin] Compose (2-1 Ex1) 상태관리, LazyRow (0) | 2023.11.10 |
[Android Kotlin] Compose (1-2 Ex1~2) Button, AlertDialog (0) | 2023.11.10 |
[Android Kotlin] Compose (1-1 Ex1~2) Row, Column, Box (0) | 2023.11.10 |