Android studio列表视频播放器
时间: 2023-08-31 18:42:05 浏览: 187
Android 列表视频
以下是一个简单的 Android Studio 列表视频播放器代码示例:
1. 在布局文件中,添加一个 RecyclerView 控件:
```
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
2. 创建一个 VideoAdapter 类来绑定数据和视图:
```
public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoViewHolder> {
private List<String> videoUrls;
public VideoAdapter(List<String> videoUrls) {
this.videoUrls = videoUrls;
}
@NonNull
@Override
public VideoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_video, parent, false);
return new VideoViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull VideoViewHolder holder, int position) {
String videoUrl = videoUrls.get(position);
holder.videoView.setVideoPath(videoUrl);
}
@Override
public int getItemCount() {
return videoUrls.size();
}
public class VideoViewHolder extends RecyclerView.ViewHolder {
VideoView videoView;
Button playButton;
public VideoViewHolder(@NonNull View itemView) {
super(itemView);
videoView = itemView.findViewById(R.id.videoView);
playButton = itemView.findViewById(R.id.playButton);
playButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (videoView.isPlaying()) {
videoView.pause();
playButton.setText("Play");
} else {
videoView.start();
playButton.setText("Pause");
}
}
});
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
playButton.setText("Play");
}
});
}
}
}
```
3. 在布局文件中,创建一个 item_video.xml 布局文件,用于显示每个视频项:
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="200dp">
<VideoView
android:id="@+id/videoView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button
android:id="@+id/playButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play"
android:layout_centerInParent="true" />
</RelativeLayout>
```
4. 在代码中,初始化 RecyclerView 和 VideoAdapter,并设置布局管理器和适配器:
```
List<String> videoUrls = new ArrayList<>();
videoUrls.add("your_video_url_1_here");
videoUrls.add("your_video_url_2_here");
// add more video urls as needed
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
VideoAdapter videoAdapter = new VideoAdapter(videoUrls);
recyclerView.setAdapter(videoAdapter);
```
注意:在使用 RecyclerView 播放在线视频时,需要在 Manifest 文件中添加网络权限:
```
<uses-permission android:name="android.permission.INTERNET" />
```
阅读全文