user1086500
user1086500

Reputation: 380

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

See bottom of this entry for an answer to this "problem".

In my app I inflate some xml views and add them to a LinearLayout, list, within a ScrollView. The XML looks like this:

<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>

I then try to give focus to one of the views I've put into 'list'. This is done by using this code :

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

If the above code results in a scroll down, the focused view get placed at the bottom of the screen and if it result in a scroll up, the focused view get placed at the top of the screen.

Is there a way to make the focused view always get placed at the top of the screen if the length of the list permits it?

Edit: This works! See accepted answer.

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>

Sample code to put somewhere in your activity or fragment

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

Upvotes: 4

Views: 6842

Answers (2)

moonLander_
moonLander_

Reputation: 86

Since I can't comment, I'm just gonna post this here.
The solution provided by Oğuzhan Döngül is correct, but if some of you can't get it running, try to do the smoothScroll inside runnable :

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

I add topOffset to give some spaces on top of the highlighted view.

source

Upvotes: 0

You can vertical scroll to specific view by using this:

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

It will make your view top of the scrollview(if there is enough height) After scrolling, you can request focus for this view.

Upvotes: 4

Related Questions