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

 卷軸視圖(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鍵的功能,也就是滾動到頂部和底部。app

可是,若是在TextView的append後面立刻調用fullScroll,會發現沒法滾動到真正的底部,這是由於Android下不少(若是不是所有的話)函數都是基於消息的,用消息隊列來保證同步,因此函數調用多數是異步操做的。當TextView調用了append會,並不等text顯示出來,而是把text的添加到消息隊列以後馬上返回,fullScroll被調用的時候,text可能尚未顯示,天然沒法滾動到正確的位置。異步

解決的方法其實也很簡單,使用post:ide

final ScrollView svResult = (ScrollView) findViewById(R.id.svResult);
svResult.post(new Runnable() {
    	public void run() {
    	    svResult.fullScroll(ScrollView.FOCUS_DOWN);
    	}
});
相關文章
相關標籤/搜索