使用RecyclerView和ViewPager2实现ExoPlayer的步骤如下:
implementation 'androidx.recyclerview:recyclerview:1.2.1'
implementation 'androidx.viewpager2:viewpager2:1.1.0'
public class ExoPlayerAdapter extends RecyclerView.Adapter<ExoPlayerAdapter.ViewHolder> {
private List<MediaItem> mediaItems;
private Context context;
private PlayerView playerView;
private SimpleExoPlayer exoPlayer;
public ExoPlayerAdapter(List<MediaItem> mediaItems, Context context) {
this.mediaItems = mediaItems;
this.context = context;
exoPlayer = new SimpleExoPlayer.Builder(context).build();
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_exoplayer, parent, false);
playerView = view.findViewById(R.id.player_view);
playerView.setPlayer(exoPlayer);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
MediaItem mediaItem = mediaItems.get(position);
MediaItem.Builder mediaItemBuilder = new MediaItem.Builder()
.setUri(mediaItem.getUri())
.setMimeType(mediaItem.getMimeType());
MediaItem builtMediaItem = mediaItemBuilder.build();
exoPlayer.setMediaItem(builtMediaItem);
exoPlayer.prepare();
exoPlayer.setPlayWhenReady(true);
}
@Override
public int getItemCount() {
return mediaItems.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(@NonNull View itemView) {
super(itemView);
}
}
}
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ExoPlayerAdapter exoPlayerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
List<MediaItem> mediaItems = new ArrayList<>();
// 添加你的音视频文件到mediaItems列表中
exoPlayerAdapter = new ExoPlayerAdapter(mediaItems, this);
recyclerView.setAdapter(exoPlayerAdapter);
}
}
activity_main.xml:
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
item_exoplayer.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.google.android.exoplayer2.ui.PlayerView
android:id="@+id/player_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
通过以上步骤,你可以使用RecyclerView和ViewPager2来实现ExoPlayer的播放功能。每个RecyclerView的item都包含一个ExoPlayer实例,可以独立播放音视频文件。
注意:以上代码示例中使用了Google的ExoPlayer库来实现音视频播放功能。你可以根据自己的需求选择其他的音视频播放库。
领取专属 10元无门槛券
手把手带您无忧上云