1. 在build.gradle中添加依赖
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.github.bumptech.glide:glide:3.7.0'
2. 在xml中添加recyclerview布局
1 <android.support.v7.widget.RecyclerView 2 android:id="@+id/rv_list" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:layout_marginBottom="55dp"> 6 </android.support.v7.widget.RecyclerView>
3. CourseAdapter适配器
1 public class CourseAdapter extends RecyclerView.Adapter<CourseAdapter.MyViewHolder> { 2 3 private Context mContext; 4 private List<CourseBean> cbl; 5 6 //通过构造获取上下文 7 public CourseAdapter(Context context) { 8 mContext = context; 9 } 10 11 /** 12 * 设置数据更新 13 * 14 * @param cbl 15 */ 16 public void setData(List<CourseBean>cbl) { 17 this.cbl = cbl; 18 notifyDataSetChanged(); 19 } 20 /** 21 * 创建ViewHolder 22 * @param parent 23 * @param viewType 24 * @return 25 */ 26 @Override 27 public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 28 View view = LayoutInflater.from(mContext).inflate(R.layout.course_list_item,parent, false); 29 MyViewHolder holder = new MyViewHolder(view); 30 return holder; 31 } 32 33 /** 34 * 绑定ViewHolder 35 * @param holder 36 * @param position 37 */ 38 @Override 39 public void onBindViewHolder(final MyViewHolder holder, final int position) { 40 //设置数据 41 holder.tv_title.setText(cbl.get(position).title); 42 holder.tv_img_title.setText(cbl.get(position).imgTitle); 43 //获取本地图片 44 //int id = mContext.getResources().getIdentifier("chapter_"+(position+1)+"_icon","drawable",mContext.getPackageName()); 45 //holder.iv_img.setImageResource(id); 46 //Glide加载网络图片 47 String url = "http://10.200.173.18:8080/resource/chapter_"+(position+1)+"_icon.png"; 48 Glide.with(mContext).load(url).into(holder.iv_img); 49 50 holder.iv_img.setOnClickListener(new View.OnClickListener() { 51 @Override 52 public void onClick(View view) { 53 Intent intent = new Intent(mContext, VideoListActivity.class); 54 intent.putExtra("id",cbl.get(position).id); 55 intent.putExtra("intro",cbl.get(position).intro); 56 mContext.startActivity(intent); 57 } 58 }); 59 } 60 61 /** 62 * 获取item 总数 63 * @return 64 */ 65 @Override 66 public int getItemCount() { 67 return cbl == null ? 0 : cbl.size(); 68 } 69 70 class MyViewHolder extends RecyclerView.ViewHolder { 71 72 TextView tv_img_title, tv_title; 73 ImageView iv_img; 74 75 public MyViewHolder(View itemView) { 76 super(itemView); 77 78 tv_title = (TextView) itemView.findViewById(R.id.tv_title); 79 tv_img_title = (TextView) itemView.findViewById(R.id.tv_img_title); 80 iv_img = (ImageView) itemView.findViewById(R.id.iv_img); 81 } 82 } 83 }
4. View进行数据显示
1 //初始化recyclerview布局 2 rv_list = (RecyclerView) mCurrentView.findViewById(R.id.rv_list); 3 //设置为2列的表格布局 4 rv_list.setLayoutManager(new GridLayoutManager(mContext,2)); 5 //创建适配器 6 adapter = new CourseAdapter(mContext); 7 //将数据添加到适配器 8 adapter.setData(cbl); 9 //将适配的数据添加到recyclerview布局中 10 rv_list.setAdapter(adapter);