首先在build.gradle导入:
implementation 'com.android.support:recyclerview-v7:26.1.0'
创建适配器:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> list;
private OnItemClickLitener mOnItemClickLitener;
public MyAdapter(List<String> list){
this.list = list;
}
//创建新View,被LayoutManager所调用
@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_videoview,parent,false);
return new ViewHolder(view);
}
//将数据与界面进行绑定的操作
@Override
public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
holder.videoView.setVideoPath(list.get(position));
}
//获取数据的数量
@Override
public int getItemCount() {
return list.size();
}
//自定义的ViewHolder,持有每个Item的的所有界面元素
public class ViewHolder extends RecyclerView.ViewHolder{
VideoView videoView;
ViewHolder(View itemView) {
super(itemView);
videoView = itemView.findViewById(R.id.video_view);
if (mOnItemClickLitener != null){
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = holder.getLayoutPosition();
mOnItemClickLitener.onItemClick(holder.itemView, pos);
}
});
}
}
public interface OnItemClickLitener {
void onItemClick(View view, int position);
}
public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener) {
this.mOnItemClickLitener = mOnItemClickLitener;
}
}
在Activity中:
private RecyclerView mRecyclerView;
private MyAdapter mAdapter;
private ViewPagerLayoutManager mLayoutManager;
private List<String> list;
在onCreate()中:
//设置RecyclerView管理器
mLayoutManager = new ViewPagerLayoutManager(getContext(), OrientationHelper.VERTICAL);
//初始化适配器
mAdapter = new MyAdapter(list);
mRecyclerView.setLayoutManager(mLayoutManager);
//设置适配器
mRecyclerView.setAdapter(mAdapter);
mAdapter..setOnItemClickLitener(new MaintenanceSupportAdapter.OnItemClickLitener() {
@Override
public void onItemClick(View view, int position) {
Toast.makeText(HomePageRepairActivity.this, position + " click", Toast.LENGTH_SHORT).show();
}
});
参考:https://blog.csdn.net/lmj623565791/article/details/45059587
网友评论