ScrollView scrolls when view resizes
I currently have a ScrollView with a LinearLayout. I am changing some content dynamically, eg. dynamically creating a long text snippet and adding dynamic layouts (buttons, etc.). This changes the height of the linear layout, which causes the ScrollView to scroll down. How do I keep the current scroll position during dynamic layout update?
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical
android:gravity="center_horizontal"
>
<!-- Dynamic Content Here -->
</LinearLayout>
</ScrollView>
+3
source to share
2 answers
One option I would like to suggest is to save the scroll position in the bundle and restore it.
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt("xPos", scrollView.getScrollX());
outState.putInt("yPos", scrollView.getScrollY());
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
int scrollX = savedInstanceState.getInt("xPos"); // Default value 0
int scrollY = savedInstanceState.getInt("yPos");
scrollView.scrollTo(scrollX, scrollY);
}
0
source to share
I think with these steps you can do it:
- Create your own scrollview that extends from the scrollview
- Define a boolean property to enable and disable scrolling
- Check boolean variable in onScollChanged method and return false if true
- Set boolean to true before adding dynamic views to it
- Set to false when adding done
I hope this helps you
0
source to share