리사이클러 뷰는 중첩된 스크롤을 구현하는 리스트 부의 세련되고 유연한 버전이다.
리사이클러 뷰는 목록을 만드는 RecyclerView 클래스만으로는 화면에 아무것도 출력되지 않는다. 그러므로 다음 구성 요소를 이용해야 한다.
리사이클러 뷰에서는 어댑터로 데이터에 접근할 수 있다.
Compose를 이용한 RecyclerView 예제
MainActivity
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
RecyclerViewTheme {
MyApp()
}
}
}
}
@Composable
fun MyApp(){
Scaffold(
content = {
HomeContent()
}
)
}
@Composable
fun HomeContent(){
val books = remember { DataProvider.bookList }
LazyColumn(
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp)
) {
items(
items = books,
itemContent = {
BookListItem(book = it)
})
}
}
@Composable
fun BookListItem(book: Book) {
Card(
modifier = Modifier
.padding(horizontal = 8.dp, vertical = 8.dp)
.fillMaxWidth(),
elevation = 2.dp,
backgroundColor = Color.White,
shape = RoundedCornerShape(corner = CornerSize(16.dp))
) {
Row {
BookImage(book)
Column(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
.align(Alignment.CenterVertically)
) {
Text(text = book.title, style = typography.h6)
Text(text = book.author, style = typography.caption)
}
}
}
}
@Composable
fun BookImage(book: Book){
Image(
painter = painterResource(id = book.ImageId),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.padding(8.dp)
.size(84.dp)
.clip(RoundedCornerShape(corner = CornerSize(16.dp)))
)
}
data class
data class Book(
val id: Int,
val title: String,
val author: String,
val ImageId: Int = 0
)
data provider(데이터 소스)
object DataProvider {
val bookList = listOf(
Book(
id = 1,
title = "Kotlin in action",
author = "A",
ImageId = R.drawable.kotlin_in_action
),
Book(
id = 2,
title = "Kotlin in action2",
author = "B",
ImageId = R.drawable.kotlin_in_action
),
Book(
id = 3,
title = "Kotlin in action3",
author = "C",
ImageId = R.drawable.kotlin_in_action
),
Book(
id = 4,
title = "Kotlin in action4",
author = "D",
ImageId = R.drawable.kotlin_in_action
),
Book(
id = 3,
title = "Kotlin in action3",
author = "C",
ImageId = R.drawable.kotlin_in_action
),
Book(
id = 3,
title = "Kotlin in action3",
author = "C",
ImageId = R.drawable.kotlin_in_action
),
Book(
id = 3,
title = "Kotlin in action3",
author = "C",
ImageId = R.drawable.kotlin_in_action
),
Book(
id = 3,
title = "Kotlin in action3",
author = "C",
ImageId = R.drawable.kotlin_in_action
),
)
}
화면
