2022年4月30日土曜日

LazyColumn/LazyRow で content types を使う

  1. LazyColumn(  
  2.     modifier = Modifier.fillMaxSize(),  
  3.     state = rememberLazyListState()  
  4. ) {  
  5.     item(  
  6.         contentType = "header"  
  7.     ) {  
  8.         Text(  
  9.             text = "Header",  
  10.             modifier = Modifier  
  11.                 .padding(16.dp)  
  12.                 .fillParentMaxWidth()  
  13.         )  
  14.     }  
  15.     items(  
  16.         count = 100,  
  17.         contentType = { "item" }  
  18.     ) {  
  19.         Text(  
  20.             text = "Item : $it",  
  21.             modifier = Modifier  
  22.                 .padding(16.dp)  
  23.                 .fillParentMaxWidth()  
  24.         )  
  25.     }  
  26. }  

2022年4月14日木曜日

WindowInsetsControllerCompat を使って status bar と navigation bar の light mode を切り替える

Material Catalog アプリのコードを読んでいて見つけたんですが、
WindowCompat.getInsetsController() で取得した WindowInsetsControllerCompat の setAppearanceLightStatusBars() と setAppearanceLightNavigationBars() を使うことで、status bar と navigation bar の light mode(light mode だとアイコンがグレーになり、dark だと白になる)をコードから切り替えることができます。

このようにアプリ用の MaterialTheme のところで SideEffect を使って切り替え処理をすると、Theme の xml で頑張らなくて良くなるので便利です。
  1. @Composable  
  2. fun MyAppTheme(  
  3.     darkTheme: Boolean = isSystemInDarkTheme(),  
  4.     content: @Composable () -> Unit  
  5. ) {  
  6.     val view = LocalView.current  
  7.     val context = LocalContext.current  
  8.     SideEffect {  
  9.         val controller = WindowCompat.getInsetsController(context.findActivity().window, view)  
  10.         controller?.isAppearanceLightStatusBars = !darkTheme  
  11.         controller?.isAppearanceLightNavigationBars = !darkTheme  
  12.     }  
  13.   
  14.     MaterialTheme(  
  15.         colors = if (!darkTheme) LightColorPalette else DarkColorPalette,,  
  16.         typography = Typography,  
  17.         shapes = Shapes,  
  18.         content = content  
  19.     )  
  20. }  
  21.   
  22. private tailrec fun Context.findActivity(): Activity =  
  23.     when (this) {  
  24.         is Activity -> this  
  25.         is ContextWrapper -> this.baseContext.findActivity()  
  26.         else -> throw IllegalArgumentException("Could not find activity!")  
  27.     }