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

时间:2016-04-02 10:11:30

标签: android android-linearlayout android-scrollview

请参阅此条目的底部以获取此“问题”的答案。

在我的应用程序中,我将一些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>

将示例代码放在您的活动或片段

view = findViewById(get_view_that_should_have_focus);
ScrollView scrollView = findViewById(R.id.scroll_list);
scrollView.smoothScrollTo(0, view.getTop());

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:0)

由于我无法发表评论,所以我只是将其发布在这里。
Oğuzhan Döngül 提供的解决方案是正确的,但如果有些人无法运行,请尝试在 runnable 中执行 smoothScroll

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

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

source