一、ScrollView滚动到顶部或者底部:
ScrollView scrollView = (ScrollView) findViewById(R.id.scroll_view);
scrollView.post(new Runnable(){
@Override
public void run(){
//滚动到底部
scrollview.fullScroll(ScrollView.FOCUS_DOWN);
//滚动到顶部
//scrollview.fullScroll(ScrollView.FOCUS_UP);
}
});
二、ScrollView滚动到指定位置:
LinearLayout llNeedToSkip = (LinearLayout) findViewById(R.id.ll_need_to_skip);
ScrollView scrollView = (ScrollView) findViewById(R.id.scroll_view);
scrollView.post(new Runnable(){
@Override
public void run(){
//滚动到指定位置(滚动要跳过的控件的高度的距离)
scrollView.scrollTo(0, llNeedToSkip.getMeasuredHeight());
//如果要平滑滚动,可以这样写
//scrollView.smoothScrollTo(0, llNeedToSkip.getMeasuredHeight());
}
});
因为ScrollView是一个“重量级”控件,类似于ListView、RecyclerView等,scrollXX()等方法是基于消息队列来同步的,所以在onCreate()方法中调用未必会马上就执行,可能在队列中等待处理,因此需要用post()方法。
我遇到的现实情况是ScrollView中嵌套了多个RecyclerView,页面比较复杂,即使采用post()方法也不能达到效果,这时候我能想到的办法就是延时:
LinearLayout llNeedToSkip = (LinearLayout) findViewById(R.id.ll_need_to_skip);
ScrollView scrollView = (ScrollView) findViewById(R.id.scroll_view);
scrollView.postDelay(new Runnable(){
@Override
public void run(){
scrollView.smoothScrollTo(0, llNeedToSkip.getMeasuredHeight());
}
}, 1000);
如果还是不行的话,就增加延时时间看看。