请求视图焦点并将其放置在 ScrollView 内的屏幕顶部

Request focus of view and place it on top of the screen within a ScrollView

请参阅此条目的底部以获得对此 "problem" 的答案。

在我的应用程序中,我膨胀了一些 xml 视图并将它们添加到 ScrollView 中的 LinearLayout 列表。 XML 看起来像这样:

<ScrollView
        android:layout_width="0dp"
        android:layout_weight="19"
        android:layout_height="wrap_content"
        android:fillViewport="true">
        <LinearLayout
            android:id="@+id/list"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
        </LinearLayout>
</ScrollView>

然后,我尝试将重点放在我对 'list' 提出的一种观点上。这是通过使用以下代码完成的:

view.getParent().requestChildFocus(view, view);

如果上面的代码导致向下滚动,聚焦视图将放置在屏幕底部,如果它导致向上滚动,聚焦视图将放置在屏幕顶部。

在列表长度允许的情况下,有没有办法让焦点视图始终位于屏幕顶部?

编辑:有效!查看已接受的答案。

XML

<ScrollView
        android:id="@+id/scroll_list"
        android:layout_width="0dp"
        android:layout_weight="19"
        android:layout_height="wrap_content"
        android:fillViewport="true">
        <LinearLayout
            android:id="@+id/list"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
        </LinearLayout>
</ScrollView>

放置在您的 activity 或片段

某处的示例代码
view = findViewById(get_view_that_should_have_focus);
ScrollView scrollView = findViewById(R.id.scroll_list);
scrollView.smoothScrollTo(0, view.getTop());

您可以使用以下方法垂直滚动到特定视图:

scrollView.smoothScrollTo(0,view.getTop());

它将使您的视图位于滚动视图的顶部(如果有足够的高度)滚动后,您可以为该视图请求焦点。

因为我不能发表评论,所以我就在这里 post。
提供的解决方案是正确的,但是如果你们中的某些人无法解决 运行,请尝试在 runnable 中执行 smoothScroll :

 val topOffset = view.height
 scrollView.post {
    scrollView.smoothScrollTo(0, view.top - topOffset)
 }

我添加 topOffset 以在突出显示的视图顶部留出一些空间。

source