在做项目需求时,遇到一个case,需要计算当前屏幕中所以ziview展示的高度,中间走了很多弯路。
废话不多说,直接上代码
public int getCurrentViewIndex() {
int firstVisibleItem = mLineManager.findFirstVisibleItemPosition();
int lastVisibleItem = mLineManager.findLastVisibleItemPosition();
int currentIndex = firstVisibleItem;
int lastHeight = 0;
for (int i = firstVisibleItem; i <= lastVisibleItem; i++) {
View view = mLineManager.getChildAt(i - firstVisibleItem);
if (null == view) {
continue;
}
int[] location = new int[2];
view.getLocationOnScreen(location);
Rect localRect = new Rect();
view.getLocalVisibleRect(localRect);
int showHeight = localRect.bottom - localRect.top;
if (showHeight > lastHeight) {
currentIndex = i;
lastHeight = showHeight;
}
}
if (currentIndex < 0) {
currentIndex = 0;
}
return currentIndex;
}
mLineManager是LinearLayoutManager;
findFirstVisibleItemPosition : 可以定位到屏幕中展示第一个item的全局索引值
findLastVisibleItemPosition: 可以定位到屏幕中展示最后一个item的全局索引值;
mLineManager.getChildAt(i - firstVisibleItem) :可以获取当前展示的子view; 开发过程中踩到的坑是利用 mLineManager.getChildAt(firstVisibleItem)来获取view,结果各种问题;
Recycleview中的子view应该只是缓存的几个view,因此不能够直接通过position获取子view。