Reputation: 380
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
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.
Upvotes: 0
Reputation: 7936
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