因項目需要仿微博播放列表,實現(xiàn)播放列表的蒙版覆蓋切換,用戶可見最大百分比的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個數(shù)
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);
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者