轉發請備註原文鏈接地址:https://www.niwoxuexi.com/blog/android/article/221.html
我們在開發的過程中,經常會遇到ScrollView滾動到底部和頂部的情況,下面是一種簡單的設置方法
1,設置ScrollView滾動到頂部
//設置ScrollView滾動到頂部 scrollView.fullScroll(ScrollView.FOCUS_UP);
2,設置ScrollView滾動到底部
//設置ScrollView滾動到頂部 scrollView.fullScroll(ScrollView.FOCUS_DOWN);
需要注意的是,該方法在頁面還沒有顯示出來的時候是不能直接調用的。
因爲Android很多函數都是基於消息隊列來同步,在addView完之後,不等於馬上就會顯示,而是在隊列中等待處理。這個時候調用會報錯
應對方法通過handler在新線程中更新:例如:
Handler handler = new Handler(); handler.post(new Runnable() { @Override public void run() { //設置ScrollView滾動到頂部 scrollView.fullScroll(ScrollView.FOCUS_UP); } });
當然網上還有另一種解決方案:有點複雜:調用用scrollTo()方法
public static void scrollToBottom(final View scroll, final View innerView) { Handler handler = new Handler(); handler.post(new Runnable() { public void run() { if (scroll == null || innerView == null) { return; } int offset = innerView.getMeasuredHeight() - scroll.getHeight(); if (offset < 0) offset = 0; scroll.scrollTo(0, offset); } }); }