1. 程式人生 > >Android仿微博/QQ空間滑動自動播放視訊功能

Android仿微博/QQ空間滑動自動播放視訊功能

最近做專案用到了滑動自動播放,下面是原理大家借鑑一下:
這裡寫圖片描述
關鍵程式碼
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 時,代表本次滑動完畢並停止滾動。

**SCROLL_STATE_TOUCH_SCROLL 手指觸屏拉動準備滾動,只觸發一次
SCROLL_STATE_FLING 持續滾動開始,只觸發一次
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類獲取檢視在螢幕座標中的可視區域。