[英]Compose Window Insets to move view up when Keyboard is Open, Kotlin IME Animation not working
我在實施本教程時遇到了一個小問題:
我試圖 position 一個Column
到整個屏幕的底部,然后當一個文本字段被聚焦時,我希望Column
高於鍵盤。
我用這段代碼實現了以下目標:
@OptIn(ExperimentalFoundationApi::class, ExperimentalLayoutApi::class)
@ExperimentalComposeUiApi
fun Modifier.bringIntoViewAfterImeAnimation(): Modifier = composed {
var focusState by remember { mutableStateOf<FocusState?>(null) }
val relocationRequester = remember { BringIntoViewRequester() }
val isImeVisible = WindowInsets.isImeVisible
LaunchedEffect(
isImeVisible,
focusState,
relocationRequester
) {
if (isImeVisible && focusState?.isFocused == false) {
relocationRequester.bringIntoView()
}
relocationRequester.bringIntoView()
}
bringIntoViewRequester(relocationRequester).onFocusChanged { focusState = it }
}
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun SpaceCreator() {
val localFocusManager = LocalFocusManager.current
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Bottom
) {
Column(
modifier = Modifier.bringIntoViewAfterImeAnimation()
.background(color = Color.Gray.copy(alpha = 0.2f))
) {
Text(
modifier = Modifier.fillMaxWidth()
.background(color = Color.Yellow.copy(alpha = 0.5f)),
text = "Top Text",
style = MaterialTheme.typography.h2
)
Text(text = "Content", style = MaterialTheme.typography.h2)
OutlinedTextField(
value = "ss",
onValueChange = { },
label = { Text("Email Address") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Email,
imeAction = ImeAction.Done,
),
keyboardActions = KeyboardActions(
onDone = { localFocusManager.clearFocus() }
)
)
OutlinedTextField(
value = "ss",
onValueChange = { },
label = { Text("Email Address") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Email,
imeAction = ImeAction.Done
),
keyboardActions = KeyboardActions(
onDone = { localFocusManager.clearFocus() }
)
)
Text(text = "Content", style = MaterialTheme.typography.h2)
}
}
}
但是,當我點擊另一個文本字段並且焦點發生變化時, Column
會再次重新定位,如下所示:
並且Column
的內容在鍵盤下移動。
我得到它是因為 animation 發生在焦點更改的事件中,但我只希望它在 IME 不活動時發生,然后我希望一切保持不變。
我不太確定該怎么做,但我只是將文本字段的鍵盤操作更改為:
imeAction = ImeAction.Done
和
keyboardActions = KeyboardActions(
onDone = { localFocusManager.clearFocus() }
)
但是用戶仍然可以點擊另一個文本字段,我需要他們這樣做,所以這會破壞可用性。 我怎樣才能解決這個問題?
任何幫助將不勝感激,謝謝,如果我能提供更多信息,請告訴我。
這篇中等文章為我解決了這個問題
示例代碼:
val coroutineScope = rememberCoroutineScope()
val bringIntoViewRequester = remember { BringIntoViewRequester() }
Column(modifier = Modifier.bringIntoViewRequester(bringIntoViewRequester)) {
BasicTextField(
modifier = modifier
.onFocusEvent { state ->
if (state.hasFocus || state.isFocused) {
coroutineScope.launch {
bringIntoViewRequester.bringIntoView()
}
}
},
...
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.