2021年6月30日水曜日

Jetpack Compose : キーボードが表示されたときに scrollable な Column 内の TextField が見えるようにスクロールする

1. accompanist-insets を入れる
  1. implementation "com.google.accompanist:accompanist-insets:$accompanist_version"  
2. Activity に android:windowSoftInputMode="adjustResize" をセットする

* accompanist-insets がちゃんと動くために必要
  1. <activity  
  2.     android:name=".RelocationRequesterSampleActivity"  
  3.     android:windowSoftInputMode="adjustResize">  
3. Activity で WindowCompat.setDecorFitsSystemWindows(window, false) する

* accompanist-insets がちゃんと動くために必要
  1. class RelocationRequesterSampleActivity : ComponentActivity() {  
  2.   
  3.     override fun onCreate(savedInstanceState: Bundle?) {  
  4.         super.onCreate(savedInstanceState)  
  5.   
  6.         WindowCompat.setDecorFitsSystemWindows(window, false)  
  7.   
  8.         setContent {  
  9.             MaterialTheme {  
  10.                 ProvideWindowInsets {  
  11.                     RelocationRequesterSample()  
  12.                 }  
  13.             }  
  14.         }  
  15.     }  
  16. }  
4. RelocationRequester を使う
  1. @OptIn(ExperimentalComposeUiApi::class)  
  2. @Composable  
  3. fun RelocationRequesterSample() {  
  4.     Column(  
  5.         modifier = Modifier  
  6.             .fillMaxSize()  
  7.             .statusBarsPadding()  
  8.             .navigationBarsWithImePadding()  
  9.             .verticalScroll(rememberScrollState())  
  10.             .padding(24.dp)  
  11.     ) {  
  12.         Spacer(  
  13.             modifier = Modifier  
  14.                 .fillMaxSize()  
  15.                 .height(600.dp)  
  16.                 .background(color = Color.LightGray)  
  17.         )  
  18.   
  19.         Spacer(modifier = Modifier.height(24.dp))  
  20.   
  21.         val relocationRequester = remember { RelocationRequester() }  
  22.         val interactionSource = remember { MutableInteractionSource() }  
  23.         val isFocused by interactionSource.collectIsFocusedAsState()  
  24.   
  25.         val ime = LocalWindowInsets.current.ime  
  26.         if (ime.isVisible && !ime.animationInProgress && isFocused) {  
  27.             LaunchedEffect(Unit) {  
  28.                 relocationRequester.bringIntoView()  
  29.             }  
  30.         }  
  31.   
  32.         var value by remember { mutableStateOf("") }  
  33.   
  34.         OutlinedTextField(  
  35.             value = value,  
  36.             onValueChange = { value = it },  
  37.             interactionSource = interactionSource,  
  38.             modifier = Modifier.relocationRequester(relocationRequester)  
  39.         )  
  40.     }  
  41. }  
ちなみに、 relocationRequester.bringIntoView() 部分をコメントアウトするとこうなる



参考


0 件のコメント:

コメントを投稿