由于需要做一个需求,基于GSYVideoPlayer对列表的视频自动播放,在此记录下。
分四个步骤
- 监听列表滑动状态
- 获取播放器控件
- 判断播放器可见状态
- 根据状态进行播放
监听滑动 recyclerView.addOnScrollListener()
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState)
{
super.onScrollStateChanged(recyclerView, newState);
// 监听滑动
FeedLiveAutoPlayHelper.autoPlay(recyclerView,newState);
}
辅助类
/**
* 列表自动播放辅助类
*/
public class FeedLiveAutoPlayHelper {
public static final String TAG = "FeedLiveAutoPlayHelper";
public static void autoPlay(RecyclerView recyclerView, int newState) {
Log.d(TAG, "[autoPlay]: newState:" + newState);
if (newState != 0) {
return;
}
//获取播放器控件
FeedLiveGSYVideoPlayer livePlayerView = getLivePlayerView(recyclerView);
if (livePlayerView == null) {
Log.d(TAG, "[autoPlay]: livePlayerView is null");
return;
}
// 判断播放器可见状态
if (!isViewVisible(livePlayerView)) {
Log.d(TAG, "[autoPlay]: is not Completely Visible");
return;
}
// 播放器的状态,没在播放才播放。。。
int currentState = livePlayerView.getCurrentState();
Log.d(TAG, "[autoPlay] : currentState:" + currentState);
if (currentState != CURRENT_STATE_NORMAL) {
Log.d(TAG, "[autoPlay]: livePlayerView is playing");
return;
}
// 开始播放
livePlayerView.startPlayLogic();
Log.d(TAG, "[autoPlay]: auto startPlayLogic");
}
/**
* 判断view是否可见
*
* @param view View
* @return boolean
*/
private static boolean isViewVisible(View view) {
if (view == null) {
return false;
}
Rect rect = new Rect();
// 可见
boolean isVisible = view.getGlobalVisibleRect(rect);
// 完全可见
boolean isCompletelyVisible = isVisible && (rect.bottom - rect.top >= view.getHeight());
// 三分之一可见
boolean isHalfVisible = isVisible && (rect.bottom - rect.top >= view.getHeight() / 3);
Log.d(TAG, "[isViewVisible]: Visible:" + isVisible);
Log.d(TAG, "[isViewVisible]: CompletelyVisible:" + isCompletelyVisible);
Log.d(TAG, "[isViewVisible]: HalfVisible:" + isHalfVisible);
return isHalfVisible;
}
/**
* 获取View
*
* @param recyclerView recyclerView
* @return FeedLiveGSYVideoPlayer
*/
private static FeedLiveGSYVideoPlayer getLivePlayerView(RecyclerView recyclerView) {
if (recyclerView == null) {
return null;
}
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
if (!(layoutManager instanceof LinearLayoutManager)) {
Log.d(TAG, "[getLivePlayerView]: layoutManager is not linear:");
return null;
}
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition();
int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
// 遍历可见子项
for (int i = firstVisibleItemPosition; i <= lastVisibleItemPosition; i++) {
RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(i);
if (viewHolder == null) {
continue;
}
if (!(viewHolder instanceof FeedLiveHolder)) {
continue;
}
// 这里换成自己的Holder
FeedLiveHolder feedLiveHolder = (FeedLiveHolder) viewHolder;
return feedLiveHolder.getGsyVideoPlayer();
}
return null;
}