Android 獲取ListView滾動距離方法
阿新 • • 發佈:2019-01-29
今天想做個導航欄漸變的效果,原來這種效果是通過監聽ScrollView的滾動距離實現的。由於首頁圖片較多,而且裡面還嵌套了ListView,大家都知道ListView巢狀在ScrollView中是需要計算高度然後全部顯示出來的,這樣ListView中的所有圖片就需要全部加載出來。在圖片做了快取的情況下,進入頁面還是會有明顯的卡頓。這時我就去掉了ScrollView,這個頁面只用ListView實現。
ScrollView滾動距離監控:
ListView滾動距離監控:在網上找了很多,什麼getScrollY();方法,什麼重寫ListView中的onScrollChanged等scrollView.setScrollViewListener(new ScrollViewListener() { @Override public void onScrollChanged(CustomScrollView scrollView, int x, int y, int oldx, int oldy) { // TODO Auto-generated method st } });
http://blog.csdn.net/dacainiao007/article/details/28268395
http://my.oschina.net/u/1177694/blog/504992
這都試過了,基本都不好用。最後終於找到下面的文章:
http://www.2cto.com/kf/201507/416142.html
實現程式碼:
listview.setOnScrollListener(new OnScrollListener() { private SparseArray recordSp = new SparseArray(0); private int mCurrentfirstVisibleItem = 0; @Override public void onScrollStateChanged(AbsListView arg0, int arg1) { // TODO Auto-generated method stub } @Override public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub mCurrentfirstVisibleItem = arg1; View firstView = arg0.getChildAt(0); if (null != firstView) { ItemRecod itemRecord = (ItemRecod) recordSp.get(arg1); if (null == itemRecord) { itemRecord = new ItemRecod(); } itemRecord.height = firstView.getHeight(); itemRecord.top = firstView.getTop(); recordSp.append(arg1, itemRecord); int h = getScrollY();//滾動距離 } } } private int getScrollY() { int height = 0; for (int i = 0; i < mCurrentfirstVisibleItem; i++) { ItemRecod itemRecod = (ItemRecod) recordSp.get(i); height += itemRecod.height; } ItemRecod itemRecod = (ItemRecod) recordSp.get(mCurrentfirstVisibleItem); if (null == itemRecod) { itemRecod = new ItemRecod(); } return height - itemRecod.top; } class ItemRecod { int height = 0; int top = 0; } });
二、獲取滾動高度
public int getScrollY() {
View c = listview.getChildAt(0);
if (c == null) {
return 0;
}
int firstVisiblePosition = listview.getFirstVisiblePosition();
int top = c.getTop();
return -top + firstVisiblePosition * c.getHeight() ;
}
三、單位時間滾動指定高度
ListView.smoothScrollBy(h, t);