[Compose 사용법] LazyColumn

이승우·2023년 5월 17일
1

XML 기반의 레이아웃에서는 List를 보여주기 위해서 RecyclerView를 사용했다. RecyclerView를 설정하기 위해서는 ViewHolder, Adapter, Adapter에서 구현해줘야 하는 함수 등이 필수적이었다.

Compose에서는 이러한 RecyclerView 구현을 위해서 LazyColumn이라는 걸 사용한다. LazyColumn에 대해서 알아보자.

LazyColumn이란?

화면에 보여지는 컴포저블만을 표시하는 Scrollable한 Column이다. 즉, 세로로 스크롤이 가능한 Column을 보여주는 것이다. LazyColumn은 화면에 보여지는 컴포저블만을 표시하기 때문에 화면 로딩 시간을 최적화 시킬 수 있어 많은 아이템이 표시되어야 할 경우, 필수적으로 사용되어야 하는 레이아웃이다. 👉 XML 기반의 레이아웃에서 RecyclerView 처럼 View를 재활용하여 효율적으로 view를 렌더링하는 것이다.

LazyColumn 사용하기

LazyColumn은 item을 기반으로 동작한다. item 하나가 자식 컴포저블에 대응되며, LazyColumnScope 내에서 아래의 item을 사용할 수 있다. 따라서 item에 해당되는 컴포저블이 필요하다.

  • item
  • items
  • itemsIndexed

1) item
item은 LazyColumn 내부에 컴포저블을 직접 넣고 싶을 때 사용하는 메소드이다.

fun item(
	key: Any? = null,
	contentType: Any? = null,
	content: @Composable LazyItemScope.() -> Unit
)

item의 LazyItemScope에 있는 컴포저블이 하나의 item으로 인식되어 모두 표시된다. 아래와 같은 코드는 2개의 Text 컴포저블이 LazyColumn에 생기게 된다.

item {
	// 아래 두 Text는 하나의 item이 된다.
	Text(
		text = "검색 결과 (${uiState.totalCount})",	
		modifier = Modifier.padding(8.dp)
	)
	Text(
		text = "검색 결과 (${uiState.totalCount})",
		modifier = Modifier.padding(8.dp)
	)
}

2) items
items는 컴포저블을 반복해서 나타내고자 할 때 사용한다.

inline fun <T> LazyListScope.items(
    items: List<T>,
    noinline key: ((item: T) -> Any)? = null,
    noinline contentType: (item: T) -> Any? = { null },
    crossinline itemContent: @Composable LazyItemScope.(item: T) -> Unit
)

items는 보여줄 목록을 필수적으로 전달하며, itemContent에는 보여줄 item을 넘기면 된다.

LazyColumn{
	items(uiState.bookModel.bookList) { item ->
    	BookInformationCard(
        	bookInformationModel = item,
            navigateToWebScreenAboutBook = viewModel::navigateToWebScreenAboutBook
            )
        }
}

3) itemsIndexed
사용법은 items와 유사하며, 다른 점은 index를 알 수 있다는 점이다.

inline fun <T> LazyListScope.itemsIndexed(
    items: List<T>,
    noinline key: ((index: Int, item: T) -> Any)? = null,
    crossinline contentType: (index: Int, item: T) -> Any? = { _, _ -> null },
    crossinline itemContent: @Composable LazyItemScope.(index: Int, item: T) -> Unit
)

Ref

profile
Android Developer

0개의 댓글