Jetpack Compose - 滚动到列中的可组合焦点 [英] Jetpack Compose - Scroll to focused composable in Column

查看:110
本文介绍了Jetpack Compose - 滚动到列中的可组合焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的用户界面:

val scrollState = rememberScrollState()
        Column(
            modifier = Modifier
                .fillMaxSize(1F)
                .padding(horizontal = 16.dp)
                .verticalScroll(scrollState)
        ) {

            TextField(...)
 // multiple textfields
             TextField(
                        //...
                        modifier = Modifier.focusOrder(countryFocus).onFocusChanged {
                            if(it == FocusState.Active) {
                               // scroll to this textfield
                            }
                        },
                    )
         }

我在此列中有多个 TextField,当其中一个聚焦时,我想将 Column 滚动到它.scrollState scrollState.smoothScrollTo(0f) 中有一个方法,但我不知道如何获得焦点 TextField 位置.

I have multiple TextFields in this column and when one of them is focused I want to scroll Column to it. There is a method in scrollState scrollState.smoothScrollTo(0f) but I have no idea how to get a focused TextField position.

更新:

我似乎找到了一个可行的解决方案.我使用了 onGloballyPositioned 并且它有效.但我不确定这是否是解决此问题的最佳方法.

It seems that I've found a working solution. I've used onGloballyPositioned and it works. But I'm not sure if it the best way of solving this.

var scrollToPosition = 0.0F

TextField(
   modifier = Modifier
    .focusOrder(countryFocus)
    .onGloballyPositioned { coordinates ->
        scrollToPosition = scrollState.value + coordinates.positionInRoot().y
    }
    .onFocusChanged {
    if (it == FocusState.Active) {
        scope.launch {
            scrollState.smoothScrollTo(scrollToPosition)
        }
    }
}
)

推荐答案

compose 中有一个新东西叫做 RelocationRequester.那为我解决了问题.我的自定义 TextField 中有类似的内容.

There is a new thing in compose called RelocationRequester. That solved the problem for me. I have something like this inside of my custom TextField.

val focused = source.collectIsFocusedAsState()
val relocationRequester = remember { RelocationRequester() }
val ime = LocalWindowInsets.current.ime
if (ime.isVisible && focused.value) {
    relocationRequester.bringIntoView()
}

这篇关于Jetpack Compose - 滚动到列中的可组合焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆