[Android] JetPack Compose 2 : 기본 구성

이석규·2023년 7월 6일
0

[Andoid] JetPack Compose 1 에서 컴포즈를 위한 설정을 마치고, 개발 문서에서 기재되어 있는 튜토리얼을 보며 Compose의 형태를 이해해보고자 한다.


1. Compose Function

기본적으로 주어진 setContentView()를 setContent{ }로 바꿔준다.

// com.com.practcompose.basic.TextView.kt

class TextView : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Text("Hello world!")
        }
    }
}

xml에서 제공하던 미리보기는 두 가지 방법으로 확인해 볼 수 있다.

  1. 구성된 함수와 별개로 미리볼 함수를 선언한다.
  2. 구성된 함수에 미리 볼 설정을 포함한 채로 선언한다.

뭔가.. xml이 더 편했던 것 같은데 굉장히 웹 개발의 냄새가 물신 나는 방식인 것 같다.

// com.com.practcompose.basic.Function.kt

@Composable
fun MessageCardNotHere(name: String) {
    Text(text = "Hello $name!")
}

@Preview(showBackground = true)
@Composable
fun PreviewNotHereMessageCard() {
    MessageCardNotHere("Preview_text")
}

@Preview
@Composable
fun MessageCardPreviewHere(@PreviewParameter(SampleUserProvider::class) name: String) {
    Text(text = "Hello $name!")
}

class SampleUserProvider : PreviewParameterProvider<String> {
    override val values = sequenceOf("Preview_text")
}

2. Layout

Column 함수로 텍스트를 Vertical 하게 정렬할 수 있다.
Row 함수로는 Horizontal 하게 정렬할 수 있다.

//com.com.practcompose.basic.ColumnFunc.kt

data class Message(val author: String, val body: String)

// 이렇게 텍스트를 선언하면, 텍스트가 겹쳐 보이게 된다. 그래서 정렬이 필요하다.
// @Composable
// fun MessageCards(msg: Message) {
//    Text(text = msg.author)
//    Text(text = msg.body)
// }


@Composable
fun MessageCards(msg: Message) {
    Row {
        Text(text = msg.author)
        Text(text = msg.body)
    }
}

@Preview
@Composable
fun PreviewMessageCards() {
    MessageCards(
        msg = Message("Colleague", "Hey, take a look at Jetpack Compose, it's great!")
    )
}

다음과 같이 이미지도 넣을 수 있다.

//com.com.practcompose.basic.**Imgae.kt**

@Composable
private fun MessageCard(msg: Message) {
    Row {
        Image(
            painter = painterResource(R.drawable.ic_launcher_background),
            contentDescription = "Contact profile picture"
        )

        Column {
            Text(text = msg.author)
            Text(text = msg.body)
        }
    }
}

3. Material Design

다음과 같은 경로로 테마를 설정할 수 있다. 색, 글꼴, 모양, 다크모드 등을 설정하여 재사용 가능하다.

4. List & Animation

리스트를 구현하기 위해 LazyColumn() 과 LazyRow() 를 사용하여 구현한다.

//com.com.practcompose.basic.ListView.kt

import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items

@Composable
fun Conversation(messages: List<Message>) {
    LazyColumn {
        items(messages) { message ->
            MessageCard(message)
        }
    }
}

@Composable
private fun MessageCard(msg: Message) { ...}

아이템 뷰의 줄 제한을 걸어주는 것도 가능합니다.

//com.com.practcompose.basic.ListView.kt

@Composable
private fun MessageCard(msg: Message) {
    // Add padding around our message
    Row(modifier = Modifier.padding(all = 8.dp)) {
        Image(...)

        // Add a horizontal space between the image and the column
        Spacer(modifier = Modifier.width(8.dp))

        // We keep track if the message is expanded or not in this
        // variable
        var isExpanded by remember { mutableStateOf(false) }

        // We toggle the isExpanded variable when we click on this Column
        Column(modifier = Modifier.clickable { isExpanded = !isExpanded }) {
            Surface(shape = MaterialTheme.shapes.medium, shadowElevation = 1.dp) {
                Text(
                    text = msg.author,
                    // 글자색 넣기
                    color = MaterialTheme.colors.secondaryVariant,
                    modifier = Modifier.padding(all = 4.dp),
                    // 폰트 넣기
                    style = MaterialTheme.typography.body2
                )
            }

            // Add a vertical space between the author and message texts
            Spacer(modifier = Modifier.height(4.dp))

            // 도형으로 둘러싸기
            Surface(shape = MaterialTheme.shapes.medium, shadowElevation = 1.dp) {
                Text(
                    text = msg.body,
                    modifier = Modifier.padding(all = 4.dp),
                    maxLines = if (isExpanded) Int.MAX_VALUE else 1,
                    style = MaterialTheme.typography.body2
                )
            }
        }
    }
}

클릭 되었을 때 색상이나 부가적인 변화를 주는 것도 가능하다.

//com.com.practcompose.basic.ListView.kt

// We keep track if the message is expanded or not in this
// variable
var isExpanded by remember { mutableStateOf(false) }
// surfaceColor will be updated gradually from one color to the other
val surfaceColor by animateColorAsState(
    if (isExpanded) MaterialTheme.colors.primary else MaterialTheme.colors.surface
)

// We toggle the isExpanded variable when we click on this Column
Column(modifier = Modifier.clickable { isExpanded = !isExpanded }) {
    Surface(shape = MaterialTheme.shapes.medium, shadowElevation = 1.dp) {
        Text(
            text = msg.author,
            // 글자색 넣기
            color = MaterialTheme.colors.secondaryVariant,
            modifier = Modifier.padding(all = 4.dp),
            // 폰트 넣기
            style = MaterialTheme.typography.body2
        )
    }

    // Add a vertical space between the author and message texts
    Spacer(modifier = Modifier.height(4.dp))

    // 도형으로 둘러싸기
    Surface(
        shape = MaterialTheme.shapes.medium,
        shadowElevation = 1.dp,
        // surfaceColor color will be changing gradually from primary to surface
        color = surfaceColor,
        // animateContentSize will change the Surface size gradually
        modifier = Modifier.animateContentSize().padding(1.dp)
    ) {
        Text(
            text = msg.body,
            modifier = Modifier.padding(all = 4.dp),
            maxLines = if (isExpanded) Int.MAX_VALUE else 1,
            style = MaterialTheme.typography.body2
        )
    }
}

다음 포스팅에서는 Compose 예제들을 분석하고 입력해보며 알게된 부분들을 정리해보고자 한다.


https://github.com/likppi10/PractCompose.git

출처 :

https://developer.android.com/jetpack/compose/tutorial?hl=ko

profile
안드안드안드

0개의 댓글