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

 更新时间:2018年12月17日 09:16:05   作者:wittybread  
这篇文章主要为大家详细介绍了XrecyclerView实现加载数据、切换不同布局功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了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);
 }
}

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

相关文章

  • Android Studio多渠道打包、自定义打包APK名称

    Android Studio多渠道打包、自定义打包APK名称

    Android Studio为我们提供了简便的方法,可以多渠道打包,一次打包所有的渠道包。这篇文章主要介绍了Android Studio多渠道打包、自定义打包APK名称,需要的朋友可以参考下
    2018-01-01
  • Android编程获取图片数据的方法详解

    Android编程获取图片数据的方法详解

    这篇文章主要介绍了Android编程获取图片数据的方法,涉及Android网络通信数据流传输及图片操作相关技巧,需要的朋友可以参考下
    2017-07-07
  • android音乐播放器监听电话状态实现代码

    android音乐播放器监听电话状态实现代码

    在手机上播放音乐的时候,我们希望监听电话的状态,当然在MID上没有电话功能,不需要监听
    2013-11-11
  • Android 显示和隐藏输入法实现代码

    Android 显示和隐藏输入法实现代码

    本文所要介绍的这个方法可以转换软件输入法在窗体中的显示状态,具体实现代码如下,感兴趣的你可以参考下哈,希望可以帮助到你
    2013-03-03
  • Android应用开发中自定义ViewGroup的究极攻略

    Android应用开发中自定义ViewGroup的究极攻略

    这里我们要演示的自定义ViewGroup中将实现多种方式排列和滑动等效果,并且涵盖子View之间Touch Event的拦截与处理等问题,完全干货,下面就为大家送上Android应用开发中自定义ViewGroup的究极实例攻略
    2016-05-05
  • Android实现长图文截图功能实例代码

    Android实现长图文截图功能实例代码

    这篇文章主要给大家介绍了关于Android实现长图文截图功能的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-11-11
  • Android实现裁剪照片功能

    Android实现裁剪照片功能

    这篇文章主要为大家详细介绍了Android实现裁剪照片功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-03-03
  • Android 实现当下最流行的吸顶效果

    Android 实现当下最流行的吸顶效果

    本文主要介绍了Android 实现当下最流行的吸顶效果的示例代码。具有很好的参考价值,下面跟着小编一起来看下吧
    2017-03-03
  • 常用Android布局文件优化技巧总结

    常用Android布局文件优化技巧总结

    Android布局加载是Android应用程序的重要组成部分,布局加载是指将 XML文件中定义的视图层次结构加载到内存中,在这篇文章中,我们将深入探讨 Android 布局加载的原理,包括 Android 布局文件的结构和布局文件的常见问题等方面,需要的朋友可以参考下
    2023-07-07
  • 实例讲解Android多线程应用开发中Handler的使用

    实例讲解Android多线程应用开发中Handler的使用

    这篇文章主要介绍了Android多线程应用开发中Handler的使用,Handle主要被用来更新UI和处理消息,需要的朋友可以参考下
    2016-01-01

最新评论