项目需求要根据滚动位置,对title实现渐隐渐现效果,因此想获取ListView滚动时的精确位置。在网上找了很多都不能达到要求,千篇一律只有获取ListView滚动到某个item的高度整个的高度,例如:item高度为30,获得值只有0,30,60,90…在找寻中发现了ScrollView重写onScrollChanged可实现需求,于是在ListView中仿照重写onScrollChanged却没有作用。最后终于找到一种方法实现,特此分享给大家。
本文参考文:http://www.2cto.com/kf/201507/416142.html
布局文件就略写了,只有个ListView,直接上核心代码:
//初始化控件
mlistview = (ListView) findViewById(R.id.mylistview);
String[] datas=new String[]{"11111","222222","333333","11111","222222","333333","11111","222222","333333"
,"11111","222222","333333","11111","222222","333333","11111","222222","333333"
,"11111","222222","333333","11111","222222","333333","11111","222222","333333"
,"11111","222222","333333","11111","222222","333333","11111","222222","333333"
,"11111","222222","333333","11111","222222","333333","11111","222222","333333"};
mlistview.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, datas));
mlistview.setOnScrollListener(new AbsListView.OnScrollListener() {
private SparseArray<ItemRecod> recordSp = new SparseArray(0);
private int mCurrentfirstVisibleItem = 0;
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
mCurrentfirstVisibleItem = firstVisibleItem;
View firstView = view.getChildAt(0);
if (null != firstView) {
ItemRecod itemRecord = recordSp.get(firstVisibleItem);
if (null == itemRecord) {
itemRecord = new ItemRecod();
}
//item高度
itemRecord.height = firstView.getHeight();
//滑动位置距顶部距离(负值)
itemRecord.top = firstView.getTop();
recordSp.append(firstVisibleItem, itemRecord);
}
Log.d("onScroll", getScrollY() + "");
}
//获取滚动精确值
private int getScrollY() {
int height = 0;
for (int i = 0; i < mCurrentfirstVisibleItem; i++) {
ItemRecod itemRecod = recordSp.get(i);
height += itemRecod.height;
}
ItemRecod itemRecod = recordSp.get(mCurrentfirstVisibleItem);
if (null == itemRecod) {
itemRecod = new ItemRecod();
}
return height - itemRecod.top;
}
class ItemRecod {
int height = 0;
int top = 0;
}
});
这样 getScrollY()就可以获取ListView滚动的精确位置了,希望此文也能帮到有同样需求的人。