Android Studio – How to stop reset to top of ScrollView
I’m currently running a constraint layout in a scrollView and currently have a textView that’s pretty far down the screen so I need to scroll down to see it. However, whenever I finish editing the textView that’s down the screen (such as changing its constraint by dragging its sides), the screen always resets to the top of the scrollView. Is there a way to prevent this from happening? Sorry if this is confusing, it’s a bit hard to explain. Please let me know if any more clarifying details are needed.
Here’s video of the issue: imgur.com/a/3libvbo
Thanks!
Here’s the xml file:
<fragment android:id="@+id/nav_host_fragment" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="wrap_content" android:layout_height="wrap_content" app:defaultNavHost="true" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:navGraph="@navigation/nav_graph" /> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" tools:layout_editor_absoluteX="308dp" tools:layout_editor_absoluteY="322dp"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="BottomOfScrollView" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" tools:layout_editor_absoluteY="1061dp" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TopOfScrollView" tools:layout_editor_absoluteX="112dp" tools:layout_editor_absoluteY="228dp" /> </androidx.constraintlayout.widget.ConstraintLayout> </ScrollView>
scrollView.postDelayed(new Runnable() { @Override public void run() { scrollView.smoothScrollTo(0, textView2.getBottom()); } }, 2000);
or
scrollView.post(new Runnable() { @Override public void run() { scrollView.smoothScrollTo(0, textView2.getBottom()); } });
Expanation: Calling postDelayed sends runnable to the Handler. after 2 seconds run method is called. ScrollViews have smoothScrollTo(x,y) used to scroll to position. If scroll is horizontal you should use value x, and if it is vertical like in OPs case you scroll on y axis. If you want scrolling to happen without delay use post() instead of postDelayed().