Gson+RecyclerView的使用

1.使用gson需添加的依赖: compile 'com.google.code.gson:gson:2.2.4'


2.初始化gson:Gson mGson = new Gson();

3.创建封装类

4.解析时需要传入两个参数(json数据;封装实体类)
  例:TextBean bean = mGson.fromJson(response, TextBean.class);

5.在封装类中得到集合数据
  例: List<TextBean.ResultBean> result = bean.getResult();

6.创建RecyclerView适配器
  1)继承RecyclerView.Adapter<ViewHolder>
  2)创建内部ViewHolder继承RecyclerView.ViewHolder;利用itemView加载控件
  3)创建构造方法传入集合数据+上下文
  4)重写继承类中的方法
    ①加载布局文件:
     View inflate = LayoutInflater.from(mContext).inflate(R.layout.main_recy, parent, false);
     MyRecyclerViewViewHolder viewHolder=new MyRecyclerViewViewHolder(inflate);
     return viewHolder;
    ②给控件传入数据:
     例:用Picasso加载json数据中的图片
     Picasso.with(MainActivity.this).load(data.get(postion).getImage).resize(500,500).error(R.mipmap.ic_launcher).into(holder.icon);     
    ③返回集合条目:
     data.size();

7.Activity中设置CardView布局样式:
  mainRecy.setLayoutManager(new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false));

8.给RecyclerView传入适配器
   mainRecy.setAdapter(new MyRecyclerViewAdapter(MainActivity.this, result));
   
原文地址:https://www.cnblogs.com/livelihood/p/6758750.html