2022年9月25日日曜日

AndroidViewBinding

  1. implementation "androidx.compose.ui:ui-viewbinding:$compose_version"  
  1. AndroidViewBinding(  
  2.     factory = ListItemBinding::inflate,  
  3.     update = {  
  4.         ...  
  5.     },  
  6.     modifier = ...,  
  7. )  
  1. AndroidViewBinding(  
  2.     factory = { inflater, parent, attachToParent ->  
  3.         ListItemBinding.inflate(inflater, parent, attachToParent).apply {  
  4.             ...  
  5.         }  
  6.     },  
  7.     update = {  
  8.         ...  
  9.     },  
  10.     modifier = ...,  
  11. )  

2022年9月17日土曜日

derivedStateOf の効果を LayoutInspector の composition count で確認する

derivedStateOf を使っていない、よくないコード
  1. val state = rememberLazyListState()  
  2.   
  3. // TODO derivedStateOf を使う  
  4. val showScrollToTopButton= state.firstVisibleItemIndex > 0  
  5.   
  6. LazyColumn(  
  7.     state = state,  
  8.     modifier = Modifier.fillMaxSize()  
  9. ) {  
  10.     ...  
  11. }  
  12.   
  13. if (showScrollToTopButton) {  
  14.     Button(  
  15.         onClick = {  
  16.             ...  
  17.         },  
  18.         ...  
  19.     ) {  
  20.         Text("scroll to top")  
  21.     }  
  22. }  
LayoutInspector で Button が表示されたあともスクロールのたびに recompose が走っているので Button の skip count が増えていっています。
  1. val showScrollToTopButton by remember {  
  2.     derivedStateOf { state.firstVisibleItemIndex > 0 }  
  3. }  
に変えると、スクロールのたびに recompose が走っていたのがなくなり、Button の skip count が増えなくなりました。