捲軸視圖(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);
}
});
}
作者“短褲黨”