這周的一個(gè)需求,需要實(shí)現(xiàn)內(nèi)容流自動(dòng)播放腮鞍,item布局在顯示區(qū)域達(dá)到1/3時(shí)開始播放值骇,或者停止播放。
1.首先需要判斷每個(gè)item中的顯示大小是否達(dá)到1/3移国,不足1/3 則視為被蓋住了
public boolean isCover() {
boolean cover = false;
Rect rect = new Rect();
// 此方法的返回值返回是否view有可見區(qū)域吱瘩,哪怕只有1px的地方可見就會(huì)返回true,傳入的rect中會(huì)存入顯示區(qū)域的大小信息
cover = mediaGroup.getGlobalVisibleRect(rect);
ViewGroup.LayoutParams params = mediaGroup.getLayoutParams();
KLog.d("Item isCover :" + rect.width()+"--"+ rect.height()+"--"+rect.top+"--"+ rect.bottom +"--para: "+params.width+" height:"+ params.height);
if (cover) {
if (rect.height() >= params.height/3) {
return false;
}
}
return true;
}
- 之后需要在Recyclerview停止滑動(dòng)時(shí)判斷當(dāng)前應(yīng)該播放的位置迹缀,還需要和上一個(gè)播放的對(duì)象進(jìn)行對(duì)比使碾,判斷是否是一個(gè)位置,first 和last 可以通過layoutmanager的findFirstVisibleItemPosition()和 findLastVisibleItemPosition() 來獲取
case RecyclerView.SCROLL_STATE_IDLE:
int newPosition = getFirstPlayPosition(first, last);
KLog.d("onScrollStateChanged SCROLL_STATE_IDLE :" + newPosition + " -- " + position);
if (newPosition == -1){
// 實(shí)踐中發(fā)現(xiàn)祝懂,linearLayoutManager 和 recyclerView的childAt方法返回的itemview大部分是空的票摇,推薦用這個(gè)方法來獲取 findViewByPosition(position)
View view =linearLayoutManager.findViewByPosition(position);
if (view != null && view instanceof ItemLayout&&((ItemLayout) view).isCover()){
JCVideoPlayerStandard.releaseAllVideos();
position = 0;
}
return;
}
// 如果新位置比原來的位置小,那么取最后一個(gè)滿足要求的item位置
if (newPosition < position){
// put down
newPosition = getLastPlayPosition(first, last);
}
if (newPosition == position){
return;
}
if (linearLayoutManager.findViewByPosition(position) != null &&
(linearLayoutManager.findViewByPosition(position) instanceof ItemLayout)) {
JCVideoPlayer.releaseAllVideos();
}
((ItemLayout) linearLayoutManager.findViewByPosition(newPosition)).playVideo();
position = newPosition;
大概內(nèi)容就是這些砚蓬,做的時(shí)候判斷顯示區(qū)域面積的時(shí)候不好弄矢门,記下來加深記憶,比較菜灰蛙,有好的意見歡迎大家提出來