SnapFlingBehaviorの紹介
LazyRowやLazyColumnにてスクロール後,中心に近い要素がセンターにSnapされるようになります.
基本的な形
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun SnapX(){
val state = rememberLazyListState()
val flingBehavior = rememberSnapFlingBehavior(state)
LazyRow(
state = state,
flingBehavior = flingBehavior
) {
//items
}
LazyList
のflingBehavior
引数に対して,rememberSnapFlingBehavior(state)
を渡すだけです.
実装例
@Preview
@Composable
fun PreviewSnaps(){
Box(modifier = Modifier.size(120.dp).clip(RoundedCornerShape(10)).background(Color.White), contentAlignment = Alignment.Center){
Box(modifier = Modifier.width(40.dp).fillMaxHeight().clip(RoundedCornerShape(20)).background(Color.LightGray))
Column(modifier = Modifier.fillMaxWidth()){
SnapX()
SnapX()
SnapX()
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun SnapX(){
val state = rememberLazyListState()
val flingBehavior = rememberSnapFlingBehavior(state)
LazyRow(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
state = state,
flingBehavior = flingBehavior
) {
items(50) {
Box(
modifier = Modifier
.height(40.dp)
.width(40.dp)
.padding(8.dp)
.clip(RoundedCornerShape(20))
.background(Color.DarkGray),
contentAlignment = Alignment.Center
) {
Text(it.toString(), fontSize = 16.sp, color = Color.White)
}
}
}
}