How to scroll to bottom in a ScrollView on activity startup
AndroidScrollAndroid Problem Overview
I am displaying some data in a ScrollView. On activity startup (method onCreate) I fill the ScrollView with data and want to scroll to the bottom.
I tried to use getScrollView().fullScroll(ScrollView.FOCUS_DOWN)
. This works when I make it as an action on button click but it doesn't work in the onCreate method.
Is there any way how to scroll the ScrollView to the bottom on activity startup? That means the view is already scrolled to the bottom when first time displayed.
Android Solutions
Solution 1 - Android
It needs to be done as following:
getScrollView().post(new Runnable() {
@Override
public void run() {
getScrollView().fullScroll(ScrollView.FOCUS_DOWN);
}
});
This way the view is first updated and then scrolls to the "new" bottom.
Solution 2 - Android
Put the following code after your data is added:
final ScrollView scrollview = ((ScrollView) findViewById(R.id.scrollview));
scrollview.post(new Runnable() {
@Override
public void run() {
scrollview.fullScroll(ScrollView.FOCUS_DOWN);
}
});
Solution 3 - Android
This works for me:
scrollview.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
scrollview.post(new Runnable() {
public void run() {
scrollview.fullScroll(View.FOCUS_DOWN);
}
});
}
});
Solution 4 - Android
You can do this in layout file:
android:id="@+id/listViewContent"
android:layout_width="wrap_content"
android:layout_height="381dp"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll">
Solution 5 - Android
scrollView.postDelayed(new Runnable() {
@Override
public void run() {
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
},1000);
Solution 6 - Android
Try this
final ScrollView scrollview = ((ScrollView) findViewById(R.id.scrollview));
scrollview.post(new Runnable() {
@Override
public void run() {
scrollview.fullScroll(ScrollView.FOCUS_DOWN);
}
});
Solution 7 - Android
Right after you append data to the view add this single line:
yourScrollview.fullScroll(ScrollView.FOCUS_DOWN);
Solution 8 - Android
This is the best way of doing this.
scrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
scrollView.post(new Runnable() {
@Override
public void run() {
scrollView.fullScroll(View.FOCUS_DOWN);
}
});
}
});
Solution 9 - Android
After initializing your UI component and fill it with data. add those line to your on create method
Runnable runnable=new Runnable() {
@Override
public void run() {
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
};
scrollView.post(runnable);