How to set the starting position of a ScrollView?
The accepted answer is not working for me. There is no direct way to set the initial position of a scroll view.
However, you can set the initial position before drawing the scroll view, like this:
rootView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
scrollView.getViewTreeObserver().removeOnPreDrawListener(this);
scrollView.setScrollY(100);
return false;
}
});
You can also use scrollView.setScrollY(100)
inside Handler
, but that will be jerky while scrolling.
Yes, that is possible:
ScrollView.scrollTo(int x, int y);
ScrollView.smoothScrollTo(int x, int y);
ScrollView.smoothScrollBy(int x, int y);
can be used for that. The x and y parameters are the coordinates to scroll to on the horizontal and vertical axis.
Example in code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
ScrollView sv = (ScrollView) findViewById(R.id.scrollView);
sv.scrollTo(0, 100);
}
In that example, once the Activity
is started, your ScrollView
will be scrolled down 100 pixels.
You can also try to delay the scrolling process:
final ScrollView sv = (ScrollView) findViewById(R.id.scrollView);
Handler h = new Handler();
h.postDelayed(new Runnable() {
@Override
public void run() {
sv.scrollTo(0, 100);
}
}, 250); // 250 ms delay
Scrollview sw = (ScrollView) findViewById(R.id.scrollView);
sw.post(new Runnable() {
public void run() {
sw.smoothScrollTo(0, 5000);
}
});