本文仿照新浪微網誌/QQ空間實作了滑動自動播放視訊的功能。
本文來自個人部落格:http://www.zhangliwei.date
如有疑問歡迎讨論,感謝您的關注。
先上效果圖
關鍵代碼
1.監聽滾動事件
首先要給listview添加setOnScrollListener監聽,注意這個監聽在recyclerView上是addOnScrollListener,也就是說下面代碼同時支援recyclerView。
public int firstVisible=0,visibleCount=0, totalCount=0;
videoList.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
switch (scrollState) {
case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
Log.e("videoTest", "SCROLL_STATE_FLING");
break;
case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
Log.e("videoTest", "SCROLL_STATE_IDLE");
autoPlayVideo(view);
break;
case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
Log.e("videoTest", "SCROLL_STATE_TOUCH_SCROLL");
break;
default:
break;
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// firstVisibleItem 目前第一個可見的item
// visibleItemCount 目前可見的item個數
if (firstVisible == firstVisibleItem) {
return;
}
firstVisible = firstVisibleItem;
visibleCount = visibleItemCount;
totalCount = totalItemCount;
}
});
監聽裡會有兩個方法,我們用onScroll方法記錄 目前第一個可見Item,以及可見Item總數,用onScrollStateChanged來監聽手滑動螢幕的整個過程。 當onScrollStateChanged 中的scrollState字段值等于SCROLL_STATE_IDLE 時,代表本次滑動完畢并停止滾動��感興趣的朋友可以自行百度另外兩個參數的意思,沒準對你的需求有幫助��。
#### 2.處理視訊邏輯
void autoPlayVideo(AbsListView view){
Log.e("videoTest", "firstVisiblePos = " + firstVisible + "visibleItemCount = " + visibleCount);
for (int i = 0; i < visibleCount; i++) {
if (view!=null&&view.getChildAt(i)!=null&&view.getChildAt(i).findViewById(R.id.videoplayer) != null) {
JCVideoPlayerStandard videoPlayerStandard1 = (JCVideoPlayerStandard) view.getChildAt(i).findViewById(R.id.videoplayer);
Rect rect = new Rect();
videoPlayerStandard1.getLocalVisibleRect(rect);
int videoheight3 = videoPlayerStandard1.getHeight();
Log.e("videoTest","i="+i+"==="+"videoheight3:"+videoheight3+"==="+"rect.top:"+rect.top+"==="+"rect.bottom:"+rect.bottom);
if (rect.top==0&&rect.bottom==videoheight3)
{
if (videoPlayerStandard1.currentState == JCVideoPlayer.CURRENT_STATE_NORMAL || videoPlayerStandard1.currentState == JCVideoPlayer.CURRENT_STATE_ERROR) {
Log.e("videoTest", videoPlayerStandard1.currentState + "======================performClick======================");
videoPlayerStandard1.startButton.performClick();
VPApplication.instance.VideoPlaying=videoPlayerStandard1;
}
return;
}
}
}
Log.e("videoTest", "======================releaseAllVideos=====================");
JCVideoPlayer.releaseAllVideos();
VPApplication.instance.VideoPlaying=null;
}
首先是根據總數循環判斷 Item 是否有視訊,如果有再利用Rect類擷取每個Item視圖在螢幕坐标中的可視區域,再根據Item顯示尺寸覺得播放或停止視訊。基本核心代碼就這些,是不是非常簡單,剩下的就去源碼看看吧⬇️⬇️?
項目源碼 autovideoplay
技術部落格 Wells’Note
視訊播放器
//一個沒怎麼有節操的開源播放器��。
compile 'fm.jiecao:jiecaovideoplayer:4.6.3'