LoginSignup
1
1

SnapFlingBehaviorを使ってLazyListのスクロールで要素を常に真ん中に表示する

Last updated at Posted at 2023-12-23

SnapFlingBehaviorの紹介

LazyRowやLazyColumnにてスクロール後,中心に近い要素がセンターにSnapされるようになります.

画面収録 2023-12-23 22.37.28.gif

基本的な形

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun SnapX(){
    val state = rememberLazyListState()
    val flingBehavior = rememberSnapFlingBehavior(state)

    LazyRow(
        state = state,
        flingBehavior = flingBehavior
    ) {
        //items
    }

LazyListflingBehavior引数に対して,rememberSnapFlingBehavior(state)を渡すだけです.

実装例

画面収録 2023-12-23 22.48.50.gif

@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)
            }
        }
    }
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1