天天看點

Android仿搜狐視訊、微視等清單播放視訊功能

最近項目中需要是實作在清單中自動播放視訊,中間遇到了些問題,終于解決,特來跟大家分享一下:

清單使用的RecyclerView 播放視訊使用MediaPlayer+TextureView。

主要思路:

1、監聽RecyclerView的滑動,開始滑動時停止正在播放的item。

2、通過LinearLayoutManager 擷取目前顯示的第一個item及最後一個item

3、RecyclerView停止滑動後,選擇item進行播放。如果目前界面隻有一個item,播放目前。如果item數量大于2個,播放第二個。如目前界面有兩個item則判定哪一個顯示的區域比較大。播放item并記錄目前position。

附上主要實作邏輯:

try { 
  int fristPos = layoutManager.findFirstVisibleItemPosition(); 
  int lastPos = layoutManager.findLastVisibleItemPosition(); 
  ViewHolder holder = null; 
  if (recyclerView.getChildCount() == 2) { 
  View fristView = recyclerView.getChildAt(0); 
  if (fristView != null) { 
   int[] location = new int[2]; 
   fristView.getLocationInWindow(location); 
   if (location[1]   0) { 
   holder = (ViewHolder) recyclerView.findViewHolderForPosition(fristPos); 
   lastPlayPosition = fristPos; 
   } 
  } 
  if (holder == null) { 
   View lastView = recyclerView.getChildAt(1); 
   if (lastView != null) { 
   int[] lastViewLocation = new int[2]; 
   lastView.getLocationInWindow(lastViewLocation); 
   if ((lastViewLocation[1] + videoHeight) < screenHeight) { 
    holder = (ViewHolder) recyclerView.findViewHolderForPosition(lastPos); 
    lastPlayPosition = lastPos; 
   } 
   } 
 
 
  } 
  } else if (recyclerView.getChildCount() == 1) { 
  holder = (ViewHolder) recyclerView.findViewHolderForPosition(fristPos); 
  lastPlayPosition = fristPos; 
  } else { 
  holder = (ViewHolder) recyclerView.findViewHolderForPosition(fristPos + 1); 
  lastPlayPosition = fristPos + 1; 
  } 
 
 
  if (holder != null) { 
  holder.play(); 
  } 
  
 } catch (Exception e) { 
  e.printStackTrace(); 
}            

複制

以上就是本文的全部内容,希望對大家的學習有所幫助。