Android 获取ListView滚动距离方法

今天想做个导航栏渐变的效果,原来这种效果是通过监听ScrollView的滚动距离实现的。由于首页图片较多,而且里面还嵌套了ListView,大家都知道ListView嵌套在ScrollView中是需要计算高度然后全部显示出来的,这样ListView中的所有图片就需要全部加载出来。在图片做了缓存的情况下,进入页面还是会有明显的卡顿。这时我就去掉了ScrollView,这个页面只用ListView实现。

ScrollView滚动距离监控:

scrollView.setScrollViewListener(new ScrollViewListener() {
	
	@Override
	public void onScrollChanged(CustomScrollView scrollView, int x, int y,
			int oldx, int oldy) {
		// TODO Auto-generated method st
	}
});
ListView滚动距离监控:在网上找了很多,什么getScrollY();方法,什么重写ListView中的onScrollChanged等

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);

你可能感兴趣的:(控件属性)