2024年11月9日土曜日

LazyRow で snap させる

SnapLayoutInfoProvider での snap 位置の指定方法が変わっていた。

左端に snap する場合、以前は
  1. SnapLayoutInfoProvider(  
  2.     lazyListState = state,  
  3.     positionInLayout = { layoutSize, itemSize, beforeContentPadding, afterContentPadding, _->  
  4.        0 // 左端  
  5.     },  
  6. )  
だったが、SnapPosition という interface が用意され、 左端の場合は用意されている SnapPosition.Start を指定すれば良くなった。 Start の他に End と Center も用意されている。
任意の位置に snap したい場合は SnapPosition の実装を用意すればよい。
  1. SnapLayoutInfoProvider(  
  2.     lazyListState = state,  
  3.     snapPosition = SnapPosition.Start,  
  4. )  
全体のコードはこんな感じ。
  1. @Composable  
  2. fun LazyRowSnapSample() {  
  3.     val state = rememberLazyListState()  
  4.     val snappingLayout = remember(state) {  
  5.         SnapLayoutInfoProvider(  
  6.             lazyListState = state,  
  7.             snapPosition = SnapPosition.Start,  
  8.         )  
  9.     }  
  10.     val flingBehavior = rememberSnapFlingBehavior(snappingLayout)  
  11.   
  12.     LazyRow(  
  13.         modifier = Modifier.fillMaxSize(),  
  14.         verticalAlignment = Alignment.CenterVertically,  
  15.         state = state,  
  16.         flingBehavior = flingBehavior,  
  17.     ) {  
  18.         items(200) {  
  19.             Box(  
  20.                 contentAlignment = Alignment.Center,  
  21.                 modifier = Modifier  
  22.                     .height(400.dp)  
  23.                     .width(300.dp)  
  24.                     .padding(8.dp)  
  25.                     .background(Color.LightGray),  
  26.             ) {  
  27.                 Text(text = it.toString(), fontSize = 32.sp)  
  28.             }  
  29.         }  
  30.     }  
  31. }  

0 件のコメント:

コメントを投稿