這周的一個需求,需要實現(xiàn)內(nèi)容流自動播放,item布局在顯示區(qū)域達到1/3時開始播放,或者停止播放。
1.首先需要判斷每個item中的顯示面積是否達到1/3,不足1/3 則視為被蓋住了? ?
public boolean isCover() {
? ? ? ? boolean cover = false;
? ? ? ? Rect rect = new Rect();
// 此方法的返回值返回是否view有可見區(qū)域,哪怕只有1px的地方可見就會返回true,傳入的rect中會存入顯示區(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;
? ? }
?2.之后需要在Recyclerview停止滑動時判斷當(dāng)前應(yīng)該播放的位置,還需要和上一個播放的對象進行對比,判斷是否是一個位置,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){
// 實踐中發(fā)現(xiàn),linearLayoutManager 和 recyclerView的childAt方法返回的itemview大部分是空的,推薦用這個方法來獲取 findViewByPosition(position)
? ? ? ? ? ? ? ? ? ? ? ? ? ? View view =linearLayoutManager.findViewByPosition(position);
? ? ? ? ? ? ? ? ? ? ? ? ? ? if (view != null && view instanceof ItemLayout&&((ItemLayout) view).isCover()){
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? JCVideoPlayerStandard.releaseAllVideos();
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? position = 0;
? ? ? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? ? ? return;
? ? ? ? ? ? ? ? ? ? ? ? }
// 如果新位置比原來的位置小,那么取最后一個滿足要求的item位置
? ? ? ? ? ? ? ? ? ? ? ? if (newPosition < position){
? ? ? ? ? ? ? ? ? ? ? ? ? ? // put down
? ? ? ? ? ? ? ? ? ? ? ? ? ? newPosition = getLastPlayPosition(first, last);
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? if (newPosition == position){
? ? ? ? ? ? ? ? ? ? ? ? ? ? return;
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? if (linearLayoutManager.findViewByPosition(position) != null &&
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? (linearLayoutManager.findViewByPosition(position) instanceof InjoyItemLayout)) {
? ? ? ? ? ? ? ? ? ? ? ? ? ? JCVideoPlayer.releaseAllVideos();
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? ((InjoyItemLayout) linearLayoutManager.findViewByPosition(newPosition)).playVideo();
? ? ? ? ? ? ? ? ? ? ? ? position = newPosition;
~~~