ScrollView當顯示超出當前頁面時自動移動到最底端

來源:互聯網
上載者:User

捲軸視圖(ScrollView)是指當擁有很多內容,一屏顯示不完時,需要通過滾動來顯示視圖。比如在做一個閱讀器的時候,文章很長,一頁顯示不完,那麼就需要使用捲軸視圖來滾動顯示下一頁。
Java代碼 
private ScrollView mScrollView; 
private LinearLayout mLayout; 
private final Handler mHandler = new Handler(); 
 
mScrollView = (ScrollView)findViewById(R.id.scroll); 
mLayout = (LinearLayout)findViewById(R.id.linearlayout);//linearlayout外層為 scroll 
mHandler.post(mScrollToBottom); 
 
private Runnable mScrollToBottom = new Runnable() {     
     @Override 
     public void run() { 
      // TODO Auto-generated method stub 
      int off = mLayout.getMeasuredHeight() - mScrollView.getHeight(); 
      if (off > 0) { 
       mScrollView.scrollTo(0, off); 
       } 
      } 
     }; 

在Android,一個單獨的TextView是無法滾動的,需要放在一個ScrollView中。ScrollView提供了一系列的函數,其中fullScroll用來實現home和end鍵的功能,也就是滾動到頂部和底部。

但是,如果在TextView的append後面馬上調用fullScroll,會發現無法滾動到真正的底部,這是因為Android下很多(如果不是全部的話)函數都是基於訊息的,用訊息佇列來保證同步,所以函數調用多數是非同步作業的。當TextView調用了append會,並不等text顯示出來,而是把text的添加到訊息佇列之後立刻返回,fullScroll被調用的時候,text可能還沒有顯示,自然無法滾動到正確的位置。

解決的方法其實也很簡單,使用post:
Java代碼 
final ScrollView svResult = (ScrollView) findViewById(R.id.svResult); 
svResult.post(new Runnable() { 
        public void run() { 
            svResult.fullScroll(ScrollView.FOCUS_DOWN); 
        } 
}); 

 

Android將ScrollView移動到最底部
scrollTo方法可以調整view的顯示位置。
在需要的地方調用以下方法即可。
scroll表示外層的view,inner表示內層的view,其餘內容都在inner裡。
注意,方法中開一個新線程是必要的。
否則在資料更新導致換行時getMeasuredHeight方法並不是最新的高度。

Java代碼 
public static void scrollToBottom(final View scroll, final View inner) { 
 
Handler mHandler = new Handler(); 
  
mHandler.post(new Runnable() { 
public void run() { 
if (scroll == null || inner == null) { 
return; 

 
int offset = inner.getMeasuredHeight() - scroll.getHeight(); 
if (offset < 0) { 
offset = 0; 

 
scroll.scrollTo(0, offset); 

}); 

 

作者“短褲黨”
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.