欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

XrecyclerView实现加载数据和切换不同布局

程序员文章站 2022-11-08 14:27:40
本文实例为大家分享了xrecyclerview实现加载数据和切换不同布局,供大家参考,具体内容如下 compile 'com.jcodecraeer:xrecyc...

本文实例为大家分享了xrecyclerview实现加载数据和切换不同布局,供大家参考,具体内容如下

compile 'com.jcodecraeer:xrecyclerview:1.3.2'//xrecyclerview

显示界面

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context="wangxuewei.bwie.com.wangxuewei1510c2071219.mainactivity">

 <relativelayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:gravity="center_vertical">

  <textview
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_margin="10dp"
   android:gravity="center"
   android:text="搜索商品" />

  <imageview
   android:id="@+id/cutimg"
   android:layout_width="30dp"
   android:layout_height="30dp"
   android:layout_alignparentright="true"
   android:layout_margin="7dp"
   android:src="@drawable/grid_icon" />

 </relativelayout>

 <textview
  android:layout_width="match_parent"
  android:layout_height="2dp"
  android:background="#c0c0c0" />

 <linearlayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_margin="10dp"
  android:orientation="horizontal">

  <edittext
   android:id="@+id/editkey"
   android:layout_width="0dp"
   android:layout_height="wrap_content"
   android:layout_weight="1"
   android:hint="请输入关键字" />

  <button
   android:id="@+id/btnsearch"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="搜索" />

 </linearlayout>

 <textview
  android:layout_width="match_parent"
  android:layout_height="2dp"
  android:background="#c0c0c0" />

 <com.jcodecraeer.xrecyclerview.xrecyclerview
  android:id="@+id/xrecyclerview"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"></com.jcodecraeer.xrecyclerview.xrecyclerview>

</linearlayout>

网格布局条目显示样式

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:gravity="center"
 android:orientation="vertical">

 <imageview
  android:id="@+id/goodsicon"
  android:layout_width="80dp"
  android:layout_height="80dp" />

 <textview
  android:id="@+id/title"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_margin="10dp"
  android:text="asdasd" />


 <textview
  android:id="@+id/price"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="asdasd" />

 <textview
  android:id="@+id/bargainprice"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_marginleft="5dp"
  android:text="asdasd"
  android:textcolor="#f00" />
</linearlayout>

列表布局

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:gravity="center_vertical"
 android:orientation="horizontal">

 <imageview
  android:id="@+id/goodsicon"
  android:layout_width="80dp"
  android:layout_height="80dp" />

 <linearlayout
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:orientation="vertical">

  <textview
   android:id="@+id/title"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_margin="10dp"
   android:text="asdasd" />

  <linearlayout
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_margin="10dp"
   android:orientation="horizontal">

   <textview
    android:id="@+id/price"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="asdasd" />

   <textview
    android:id="@+id/bargainprice"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginleft="5dp"
    android:text="asdasd"
    android:textcolor="#f00" />
  </linearlayout>

 </linearlayout>

</linearlayout>

主界面

public class mainactivity extends appcompatactivity implements shopsearchviewapi, view.onclicklistener {

 private imageview cutimg;
 private button btnsearch;
 private list<goodsbean.databean> list = new arraylist<>();
 private xrecyclerview xr;
 private edittext editkey;
 private int flag = 1;
 private myadapter myadapter;
 private int i = 1;
 private string string = "手机";
 private string name;

 @override
 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.activity_main);
  //加载控件
  initview();
  getdata("手机", "1");

  //设置可上拉
  xr.setpullrefreshenabled(true);
  xr.setloadingmoreenabled(true);
  //设置上拉下拉样式
  xr.setrefreshprogressstyle(progressstyle.ballspinfadeloader);
  xr.setlaodingmoreprogressstyle(progressstyle.ballcliprotate);

  clicklistener();

  xr.setloadinglistener(new xrecyclerview.loadinglistener() {
   @override
   public void onrefresh() {
    i = 1;
    list.clear();
    getdata(string, "" + i);
    xr.refreshcomplete();
   }

   @override
   public void onloadmore() {
    i++;
    getdata(string, "" + i);
    xr.loadmorecomplete();
   }
  });


 }

 public void getdata(string key, string page) {
  shopsearchpresenter shopsearchpresenter = new shopsearchpresenter(this, this);
  shopsearchpresenter.getgoodsdata("http://120.27.23.105/product/searchproducts", key, page);
 }

 private void clicklistener() {
  cutimg.setonclicklistener(this);
  btnsearch.setonclicklistener(this);
 }

 private void initview() {
  cutimg = (imageview) findviewbyid(r.id.cutimg);
  btnsearch = (button) findviewbyid(r.id.btnsearch);
  xr = (xrecyclerview) findviewbyid(r.id.xrecyclerview);
  editkey = (edittext) findviewbyid(r.id.editkey);
 }

 @override
 public void getsuccess(object o) {
  goodsbean o1 = (goodsbean) o;
  list<goodsbean.databean> data = o1.getdata();
  list.addall(data);
  setmyadapter(flag);
 }

 @override
 public void getfailed(exception e) {

 }

 @override
 public void onclick(view v) {
  switch (v.getid()) {
   case r.id.cutimg:
    if (flag == 1) {
     cutimg.setimageresource(r.drawable.lv_icon);
     flag = 2;
    } else {
     cutimg.setimageresource(r.drawable.grid_icon);
     flag = 1;
    }
    setmyadapter(flag);
    break;
   case r.id.btnsearch:
    list.clear();
    name = editkey.gettext().tostring();
    string = name;
    getdata(string, "1");
    break;
  }
 }

 public void setmyadapter(int f) {
  if (f == 1) {
   // 线性布局管理器 vertical默认样式/竖向显示  第三个参数是数据是否到过来显示
   linearlayoutmanager manager = new linearlayoutmanager(this, linearlayoutmanager.vertical, false);
   //添加布局管理器
   xr.setlayoutmanager(manager);
   myadapter = new myadapter(list, this, f);
   xr.setadapter(myadapter);
  } else if (f == 2) {
   // 线性布局管理器 vertical默认样式/竖向显示  第三个参数是数据是否到过来显示
   gridlayoutmanager gridlayoutmanager = new gridlayoutmanager(this, 2, gridlayoutmanager.vertical, false);
   //添加布局管理器
   xr.setlayoutmanager(gridlayoutmanager);
   myadapter = new myadapter(list, this, f);
   xr.setadapter(myadapter);
  }
 }
}

myadapter

public class myadapter extends recyclerview.adapter<myadapter.myviewholder> {
 private list<goodsbean.databean> list;
 private context context;
 private int flag = 1;
 private view inflate;

 public myadapter(list<goodsbean.databean> list, context context, int flag) {
  this.list = list;
  this.context = context;
  this.flag = flag;
 }

 @override
 public myadapter.myviewholder oncreateviewholder(viewgroup parent, int viewtype) {
  if (flag == 1) {
   inflate = layoutinflater.from(context).inflate(r.layout.lvitem, parent, false);
  } else if (flag == 2) {
   inflate = layoutinflater.from(context).inflate(r.layout.griditem, parent, false);
  }

  myviewholder myviewholder = new myviewholder(inflate);

  return myviewholder;
 }

 @override
 public void onbindviewholder(myadapter.myviewholder holder, int position) {

  string images = list.get(position).getimages();
  string[] split = images.split("\\|");
  glide.with(context).load(split[0]).into(holder.icon);
  holder.title.settext(list.get(position).gettitle());
  holder.bargainprice.settext("折扣价:" + list.get(position).getbargainprice() + "");
  holder.price.settext("原价:" + list.get(position).getprice());
  holder.price.getpaint().setflags(paint.strike_thru_text_flag);

 }

 @override
 public int getitemcount() {
  return list != null ? list.size() : 0;
 }

 class myviewholder extends recyclerview.viewholder {

  private imageview icon;
  private textview title;
  private textview bargainprice;
  private textview price;

  public myviewholder(view itemview) {
   super(itemview);

   icon = (imageview) itemview.findviewbyid(r.id.goodsicon);
   title = (textview) itemview.findviewbyid(r.id.title);
   bargainprice = (textview) itemview.findviewbyid(r.id.bargainprice);
   price = (textview) itemview.findviewbyid(r.id.price);

  }
 }

}

shopsearchmodle

public class shopsearchmodle {


 public void getdata(string url, map<string, string> map, final shopsearchpresenterapi shopsearchpresenterapi) {
  httputils.getinstance().get(url, map, new callback() {
   @override
   public void onsuccess(object o) {
    shopsearchpresenterapi.success(o);
   }

   @override
   public void onfailed(exception e) {
    shopsearchpresenterapi.failed(e);
   }
  }, goodsbean.class);
 }


}

shopsearchpresenter

public class shopsearchpresenter {

 private shopsearchviewapi shopsearchviewapi;
 private context context;
 private final shopsearchmodle shopsearchmodle;

 public shopsearchpresenter(shopsearchviewapi shopsearchviewapi, context context) {
  this.shopsearchviewapi = shopsearchviewapi;
  this.context = context;
  shopsearchmodle = new shopsearchmodle();
 }

 public void getgoodsdata(string url, string keywords, string page) {
  map<string, string> map = new hashmap<>();
  map.put("keywords", keywords);
  map.put("page", page);
  shopsearchmodle.getdata(url, map, new shopsearchpresenterapi() {
   @override
   public void success(object o) {
    shopsearchviewapi.getsuccess(o);
   }

   @override
   public void failed(exception e) {
    shopsearchviewapi.getfailed(e);
   }
  });
 }


}

shopsearchpresenterapi

public interface shopsearchpresenterapi {

 void success(object o);

 void failed(exception e);


}

重点内容

package wangxuewei.bwie.com.wangxuewei1510c2071219;

/**
 * created by jim on 2017/12/19.
 */

public interface shopsearchviewapi {

 void getsuccess(object o);

 void getfailed(exception e);


}

httputils

public class httputils {

 private static volatile httputils instance;

 private static handler handler = new handler();

 private httputils() {

 }

 public static httputils getinstance() {
  if (instance == null) {
   synchronized (httputils.class) {
    if (instance == null) {
     instance = new httputils();
    }
   }
  }
  return instance;
 }

 //get请求
 public void get(string url, map<string, string> map, final callback callback, final class c) {
  //对url和参数做拼接处理
  stringbuffer stringbuffer = new stringbuffer();
  stringbuffer.append(url);
  //判断是否存在? if中是存在
  if (stringbuffer.indexof("?") != -1) {
   //判断?是否在最后一位 if中是不在最后一位
   if (stringbuffer.indexof("?") != stringbuffer.length() - 1) {
    stringbuffer.append("&");
   }
  } else {
   stringbuffer.append("?");
  }
  for (map.entry<string, string> entry : map.entryset()) {
   stringbuffer.append(entry.getkey())
     .append("=")
     .append(entry.getvalue())
     .append("&");
  }
  //判断是否存在& if中是存在
  if (stringbuffer.indexof("&") != -1) {
   stringbuffer.deletecharat(stringbuffer.lastindexof("&"));
  }


  //1:创建okhttpclient对象
  okhttpclient okhttpclient = new okhttpclient.builder().addinterceptor(new logger()).build();
  //2:创建request对象
  final request request = new request.builder()
    .get()
    .url(stringbuffer.tostring())
    .build();
  //3:创建call对象
  call call = okhttpclient.newcall(request);
  //4:请求网络
  call.enqueue(new callback() {
   //请求失败
   @override
   public void onfailure(call call, final ioexception e) {
    handler.post(new runnable() {
     @override
     public void run() {
      callback.onfailed(e);
     }
    });
   }

   //请求成功
   @override
   public void onresponse(call call, response response) throws ioexception {
    string result = response.body().string();
    //拿到数据解析
    final object o = new gson().fromjson(result, c);
    //当前是在子线程,回到主线程中
    handler.post(new runnable() {
     @override
     public void run() {
      //回调
      callback.onsuccess(o);
     }
    });
   }
  });

 }

 //post请求
 public void post(string url, map<string, string> map, final callback callback, final class c) {
  //1:创建okhttpclient对象
  okhttpclient okhttpclient = new okhttpclient();
  //2:提供post请求需要的body对象
  formbody.builder builder = new formbody.builder();
  for (map.entry<string, string> entry : map.entryset()) {
   builder.add(entry.getkey(), entry.getvalue());
  }
  formbody body = builder.build();
  //3:创建request对象
  final request request = new request.builder()
    .post(body)
    .url(url)
    .build();
  //4:创建call对象
  call call = okhttpclient.newcall(request);
  //5:请求网络
  call.enqueue(new callback() {
   //请求失败
   @override
   public void onfailure(call call, final ioexception e) {
    handler.post(new runnable() {
     @override
     public void run() {
      callback.onfailed(e);
     }
    });
   }

   //请求成功
   @override
   public void onresponse(call call, response response) throws ioexception {
    string result = response.body().string();
    //拿到数据解析
    final object o = new gson().fromjson(result, c);
    //当前是在子线程,回到主线程中
    handler.post(new runnable() {
     @override
     public void run() {
      //回调
      callback.onsuccess(o);
     }
    });
   }
  });
 }

}

重点内容

public interface callback {

 void onsuccess(object o);

 void onfailed(exception e);

}

logger

public class logger implements interceptor {
 @override
 public response intercept(chain chain) throws ioexception {
  request original = chain.request();
  httpurl url = original.url().newbuilder()
    .addqueryparameter("source", "android")
    .build();
  //添加请求头
  request request = original.newbuilder()
    .url(url)
    .build();
  return chain.proceed(request);
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。