반응형
1. LazyColumn
LazyColumn은 Jetpack Compose에서 큰 데이터 목록을 효율적으로 표시할 수 있게 해주는 컴포저블이다. 즉 흔히 사용하던 RecyclerView와 같이 재사용이 가능한 Composable 함수인 것이다. 눈에 보이는 항목만 구성하고 배치하여 Column보다 성능이 뛰어나다.
- Composable 함수: LazyColumn은 컴포저블 함수이므로 @Composable 범위 내에서 사용된다.
- 항목: items, item, itemsIndexed와 같은 함수를 사용하여 LazyColumn에 표시할 항목 목록을 지정할 수 있다.
- 지연 로딩: 화면에 보이는 항목만 구성되어 성능이 향상된다.(재사용성)
CODE
import android.os.Bundle
androidx.activity.ComponentActivity
androidx.activity.compose.setContent
androidx.compose.foundation.layout.fillMaxSize
androidx.compose.foundation.lazy.LazyColumn
androidx.compose.foundation.lazy.items
androidx.compose.material3.MaterialTheme
androidx.compose.material3.Surface
androidx.compose.material3.Text
androidx.compose.runtime.Composable
androidx.compose.ui.Modifier
androidx.compose.ui.tooling.preview.Preview
androidx.compose.ui.unit.dp
androidx.compose.ui.unit.sp
androidx.compose.foundation.layout.padding
androidx.compose.ui.graphics.Color
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApp {
MyLazyColumn()
}
}
}
}
@Composable
fun MyApp(content: @Composable () -> Unit) {
MaterialTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
content()
}
}
}
@Composable
fun MyLazyColumn() {
val itemsList = List(100) { "항목 $it" } // 100개의 items 항목 생성
LazyColumn(
modifier = Modifier.padding(16.dp)
) {
items(itemsList) { item ->
Text(
text = item,
fontSize = 20.sp,
modifier = Modifier.padding(vertical = 8.dp),
color = Color.Black
)
}
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
MyApp {
MyLazyColumn()
}
}
각 메서드는 컴포저블 함수로 "LayColumn" 컴포저블 함수를 렌더링 하기 위해 구성했다.
- MyApp: 앱의 테마와 배경을 설정하는 컴포저블 함수이다.
- MyLazyColumn: 100개의 항목 목록을 가진 LazyColumn을 설정하는 함수이다. items 함수를 사용하여 표시할 항목 목록을 지정한다.
- LazyColumn: LazyColumn 내에서 items 함수를 사용하여 목록의 각 항목을 표시한다. 각 항목은 "RecyclerView" 에서 "list_item.xml"과 같은 Text 컴포저블이다.
용도와 구조는 RecyclerView와 비슷하다. item_list.xml을 holder에 담아 각 리스트에 넣어 보여주는 RecyclerView와 같이 items에 있는 각 item을 LazyColumn에 담아 컴포저블함수 item을 렌더링 하는 것이다. 당연히 화면에 보이는 컴포저블 함수만 렌더링 한다. 초창기 선언형 UI가 나온지 얼마 안되었을 땐 RecyclerView와 컴포즈를 사용한 리스트를 표현하는 방법에 대해 많은 글이 올라왔지만 LazyColum이 있는 시점에서 사용할 용도가 있을까 하는 생각이 든다. 선언형 UI는 코드 간소화 부분에 있어 많은 장점이 있는 것 같다.
반응형
'Android > Android Kotlin' 카테고리의 다른 글
[Android Kotlin] Navigation (0) | 2024.08.02 |
---|---|
[Android Kotlin] Scaffold (0) | 2024.08.02 |
[Android Kotlin] Compose (2-2 Ex1~2) Button, ShoppingMall (0) | 2023.11.10 |
[Android Kotlin] Compose (2-1 Ex1) 상태관리, LazyRow (0) | 2023.11.10 |
[Android Kotlin] Compose (1-2 Ex1~2) Button, AlertDialog (0) | 2023.11.10 |