因项目需要仿微博播放列表,实现播放列表的蒙版覆盖切换,用户可见最大百分比的item的position查找
public class RecycleViewPercentItem {
private VisibleItem mVisibleItem;
private int percentPosition = -1;
private int lastPercentPosition = -1;
public RecycleViewPercentItem(VisibleItem mVisibleItem) {
this.mVisibleItem = mVisibleItem;
}
//初始最大百分比的位置
public void setPercentPosition(int percentPosition) {
this.percentPosition = percentPosition;
}
//RecyclerView,列表的最大长度
public void getItemVisible(RecyclerView recyclerView, int maxSize) {
lastPercentPosition = percentPosition;
LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
//获取可见item个数
int childCount = manager.findLastVisibleItemPosition() - manager.findFirstVisibleItemPosition() + 1;
//第一个可见item的位置
int firstVisible = manager.findFirstVisibleItemPosition();
Map<Integer, Integer> percents = new HashMap<>();
for (int i = 0; i < childCount; i++) {
//取出所有可见itemview
View view = manager.findViewByPosition(firstVisible + i);
int position = firstVisible + i;
if (position >= maxSize) {
break;
}
KLog.e("可见位置:" + position + ",可见百分比:" + getVisibilityPercents(view));
percents.put(getVisibilityPercents(view), position);
}
if (percents.size() > 0) {
//取出百分比最大的position
Set<Integer> set = percents.keySet();
percentPosition = percents.get(Collections.max(set));
}
if (lastPercentPosition == percentPosition) {
return;
}
mVisibleItem.maxPercentPosition(percentPosition, lastPercentPosition);
}
private int getVisibilityPercents(View view) {
Rect rect = new Rect();
view.getLocalVisibleRect(rect);
int height = view.getHeight();
int percents = 100;
if (rect.top == 0 && rect.bottom == height) {
percents = 100;
} else if (rect.top > 0) {
percents = (height - rect.top) * 100 / height;
} else if (rect.bottom > 0 && rect.bottom < height) {
percents = rect.bottom * 100 / height;
}
return percents;
}
public interface VisibleItem {
//当前可见最大百分比的position,上次可见最大百分比的position
void maxPercentPosition(int percentPosition, int lastPercentPosition);
}
}