1

也许这是正常行为,但我希望它有所不同。我曾尝试用谷歌搜索解决方案,但没有找到任何合适的(或只是错过了)。

示例代码(为简单起见,我在这里持有可变状态,不使用 ViewModel):

@Composable
fun Greeting() {
    Scaffold(topBar = {
        TopAppBar(title = { Text(text = "Some title") })
    }) {
        val focusManager = LocalFocusManager.current
        LazyColumn(
            contentPadding = PaddingValues(all = 16.dp),
            verticalArrangement = Arrangement.spacedBy(space = 16.dp)
        ) {
            items(count = 20) { index ->
                val (value, onValueChange) = rememberSaveable { mutableStateOf("Some value $index") }
                TextField(
                    value = value,
                    onValueChange = onValueChange,
                    modifier = Modifier.fillMaxWidth(),
                    label = { Text(text = "Some label $index") },
                    keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
                    keyboardActions = KeyboardActions(onNext = {
                        if (!focusManager.moveFocus(FocusDirection.Down))
                            focusManager.clearFocus()
                    }),
                    singleLine = true
                )
            }
        }
    }
}

撰写版本 1.0.5

4

1 回答 1

0

您可以尝试在发生滚动时隐藏键盘。只要您没有大量物品,这没关系。但是由于您使用的是 TextFields,因此您不可能拥有这么多的数字。此示例说明了在发生滚动时隐藏键盘:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        startActivity(intent)

        setContent {
            Greeting(this)
        }
    }
}

@Composable
fun Greeting(activity: Activity) {

    Scaffold(topBar = {
        TopAppBar(title = { Text(text = "Some title") })
    }) {

        val lazyListState = rememberLazyListState()
        val ctx = LocalContext.current

        LaunchedEffect(lazyListState.firstVisibleItemIndex) {
            val inputMethodManager = ctx.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputMethodManager.hideSoftInputFromWindow(activity.window?.decorView?.windowToken, 0)
        }

        LazyColumn(
            state = lazyListState,
            contentPadding = PaddingValues(all = 16.dp),
            verticalArrangement = Arrangement.spacedBy(space = 16.dp)
        ) {
            items(
                count = 20,
                key = { index ->
                    // Return a stable + unique key for the item
                    index
                }
            ) { index ->
                val (value, onValueChange) = rememberSaveable { mutableStateOf("Some value $index") }
                TextField(
                    value = value,
                    onValueChange = onValueChange,
                    modifier = Modifier
                        .fillMaxWidth(),
                    label = { Text(text = "Some label $index") },
                    singleLine = true
                )
            }
        }
    }
}
于 2021-12-08T14:00:25.263 回答