先写框架:
model类
public static Result goodsList(String keywords, final String page) { String resultString = HttpUtils.postForm("http://www.zhaoapi.cn/product/searchProducts", new String[]{"keywords", "page"}, new String[]{keywords, page}); try { Gson gson = new Gson(); Type type = new TypeToken<Result<List<Goods>>>() { }.getType(); Result result = gson.fromJson(resultString, type); return result; } catch (Exception e) { } Result result = new Result(); result.setCode(-1); result.setMsg("数据解析异常"); return result; } }
core类
public abstract class BasePresenter { DataCall dataCall; public BasePresenter(DataCall dataCall){ this.dataCall = dataCall; } Handler mHandler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { Result result = (Result) msg.obj; if (result.getCode()==0){ dataCall.success(result.getData()); }else{ dataCall.fail(result); } } }; public void requestData(final Object...args){ new Thread(new Runnable() { @Override public void run() { Message message = mHandler.obtainMessage(); message.obj = getData(args); mHandler.sendMessage(message); } }).start(); } protected abstract Result getData(Object...args); public void unBindCall(){ this.dataCall = null; } }
public interface DataCall<T> { void success(T data); void fail(Result result); }
public class DTApplication extends Application { private static DTApplication instance; private SharedPreferences mSharedPreferences; @Override public void onCreate() { super.onCreate(); instance = this; mSharedPreferences = getSharedPreferences("application", Context.MODE_PRIVATE); } public static DTApplication getInstance() { return instance; } public SharedPreferences getShare() { return mSharedPreferences; } }
Presenter类
public class MyPresenter extends BasePresenter { private int page=1; private boolean isRefresh = true; public MyPresenter(DataCall dataCall) { super(dataCall); } @Override protected Result getData(Object[] args) { isRefresh = (boolean) args[0]; if (isRefresh){ page = 1; }else { page++; } Result result = GoodsListModel.goodsList((String)args[1],page+""); return result; } public boolean isRefresh(){ return isRefresh; } }
Util类
public class HttpUtils { public static String get(String urlString){ OkHttpClient okHttpClient = new OkHttpClient(); Request request = new Request.Builder().url(urlString).get().build(); try { Response response = okHttpClient.newCall(request).execute(); return response.body().string(); } catch (IOException e) { e.printStackTrace(); } return ""; } public static String postForm(String url,String[] name,String[] value){ OkHttpClient okHttpClient = new OkHttpClient(); FormBody.Builder formBuild = new FormBody.Builder(); for (int i = 0; i < name.length; i++) { formBuild.add(name[i],value[i]); } Request request = new Request.Builder().url(url).post(formBuild.build()).build(); try { Response response = okHttpClient.newCall(request).execute(); String result = response.body().string(); Log.i("dt",result); return result; } catch (IOException e) { e.printStackTrace(); } return ""; } public static String postFile(String url,String[] name,String[] value,String fileParamName,File file){ OkHttpClient okHttpClient = new OkHttpClient(); MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM); if(file != null){ // MediaType.parse() 里面是上传的文件类型。 RequestBody body = RequestBody.create(MediaType.parse("image/*"), file); String filename = file.getName(); // 参数分别为: 文件参数名 ,文件名称 , RequestBody requestBody.addFormDataPart(fileParamName, "jpg", body); } if (name!=null) { for (int i = 0; i < name.length; i++) { requestBody.addFormDataPart(name[i], value[i]); } } Request request = new Request.Builder().url(url).post(requestBody.build()).build(); try { Response response = okHttpClient.newCall(request).execute(); if (response.code()==200) { return response.body().string(); } } catch (IOException e) { e.printStackTrace(); } return ""; } public static String postJson(String url,String jsonString){ OkHttpClient okHttpClient = new OkHttpClient(); RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),jsonString); Request request = new Request.Builder().url(url).post(requestBody).build(); try { Response response = okHttpClient.newCall(request).execute(); return response.body().string(); } catch (IOException e) { e.printStackTrace(); } return ""; } }
主页面布局
<?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" > <RelativeLayout android:layout_width="match_parent" android:layout_height="50dp" android:focusable="true" android:focusableInTouchMode="true"> <ImageView android:id="@+id/btn_back" android:layout_width="50dp" android:layout_height="50dp" android:layout_alignParentLeft="true" android:padding="15dp" /> <ImageView android:id="@+id/btn_layout" android:layout_width="50dp" android:layout_height="50dp" android:layout_alignParentRight="true" android:padding="15dp" /> <EditText android:id="@+id/edit_keywords" android:layout_width="match_parent" android:layout_height="36dp" android:layout_centerVertical="true" android:layout_marginRight="5dp" android:layout_toLeftOf="@+id/btn_layout" android:layout_toRightOf="@+id/btn_back" android:hint="搜索" android:paddingLeft="40dp" android:singleLine="true" android:text="手机" android:textSize="16sp" /> <ImageView android:id="@+id/btn_search" android:layout_width="30dp" android:layout_height="30dp" android:layout_alignLeft="@+id/edit_keywords" android:layout_centerVertical="true" android:layout_marginLeft="10dp" android:src="@android:drawable/ic_search_category_default" /> <ImageView android:layout_width="30dp" android:layout_height="30dp" android:layout_alignRight="@+id/edit_keywords" android:layout_centerVertical="true" android:layout_marginRight="10dp" /> </RelativeLayout> <ImageView android:layout_width="match_parent" android:layout_height="1dp" android:src="@android:color/darker_gray" /> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" android:orientation="horizontal"> <TextView android:id="@+id/cate_text1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:text="综合▲" android:textSize="14sp"></TextView> <TextView android:id="@+id/cate_text2" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:text="价格▲" android:textSize="14sp"></TextView> <TextView android:id="@+id/cate_text3" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:text="销量▲" android:textSize="14sp"></TextView> <TextView android:id="@+id/cate_text4" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:text="筛选▲" android:textSize="14sp"></TextView> </LinearLayout> <ImageView android:layout_width="match_parent" android:layout_height="1dp" android:src="@android:color/darker_gray" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <com.jcodecraeer.xrecyclerview.XRecyclerView android:id="@+id/list_goods" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_width="match_parent" android:layout_height="match_parent"> </com.jcodecraeer.xrecyclerview.XRecyclerView> <ImageView android:id="@+id/shop_car" android:layout_width="40dp" android:layout_height="40dp" android:layout_alignParentRight="true" android:layout_alignParentBottom="true" android:layout_margin="50dp" /> </RelativeLayout> </LinearLayout>
主页面代码
public class MainActivity extends AppCompatActivity implements XRecyclerView.LoadingListener, DataCall<List<Goods>>,View.OnClickListener,GoodsListAdapter.OnItemClickListener { private ImageView mBtnLayout; private EditText editText; private XRecyclerView xRecyclerView; private GridLayoutManager gridLayoutManager; private LinearLayoutManager linearLayoutManager; private GoodsListAdapter goodsListAdapter; private MyPresenter mPresenter = new MyPresenter(this); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = findViewById(R.id.edit_keywords); mBtnLayout = findViewById(R.id.btn_layout); findViewById(R.id.btn_search).setOnClickListener(this); findViewById(R.id.shop_car).setOnClickListener(this); mBtnLayout.setOnClickListener(this); xRecyclerView = findViewById(R.id.list_goods); xRecyclerView.setLoadingListener(this); gridLayoutManager = new GridLayoutManager(this,2,GridLayoutManager.VERTICAL,false); linearLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false); xRecyclerView.setLayoutManager(linearLayoutManager); goodsListAdapter = new GoodsListAdapter(this); goodsListAdapter.setOnItemClickListener(this); xRecyclerView.setAdapter(goodsListAdapter); } @Override public void success(List<Goods> data) { xRecyclerView.refreshComplete(); xRecyclerView.loadMoreComplete(); if (mPresenter.isRefresh()){ goodsListAdapter.clearList(); } goodsListAdapter.addAll(data); goodsListAdapter.notifyDataSetChanged(); } @Override public void fail(Result result) { xRecyclerView.refreshComplete(); xRecyclerView.loadMoreComplete(); Toast.makeText(this,result.getCode()+""+result.getMsg(),Toast.LENGTH_LONG).show(); } @Override public void onRefresh() { String keywords = editText.getText().toString(); mPresenter.requestData(true,keywords); } @Override public void onLoadMore() { String keywords = editText.getText().toString(); mPresenter.requestData(false,keywords); } private boolean isGrid = false; @Override protected void onDestroy() { super.onDestroy(); mPresenter.unBindCall(); } @Override public void onClick(View v) { if (v.getId()==R.id.btn_search){ String keywords = editText.getText().toString(); mPresenter.requestData(true,keywords); }else if(v.getId()==R.id.btn_layout){ if (xRecyclerView.getLayoutManager().equals(linearLayoutManager)) { isGrid = true; goodsListAdapter.setViewType(GoodsListAdapter.GRID_TYPE); xRecyclerView.setLayoutManager(gridLayoutManager); } else { isGrid = false; goodsListAdapter.setViewType(GoodsListAdapter.LINEAR_TYPE); xRecyclerView.setLayoutManager(linearLayoutManager); } goodsListAdapter.notifyDataSetChanged(); } } @Override public void onItemClick(Goods goods) { Intent intent = new Intent(this,WebActivity.class); intent.putExtra("url",goods.getDetailUrl()); startActivity(intent); } }
XML页面
goods_grid_item.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ImageView android:id="@+id/image" android:layout_width="match_parent" android:layout_height="wrap_content" android:adjustViewBounds="true" android:minHeight="50dp" android:src="@mipmap/ic_launcher"/> <TextView android:id="@+id/text" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="aa" android:padding="10dp"/> </LinearLayout>
goods_linear_item.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <ImageView android:id="@+id/image" android:layout_margin="10dp" android:layout_width="100dp" android:layout_height="wrap_content" android:adjustViewBounds="true" android:minHeight="50dp" android:src="@mipmap/ic_launcher"/> <TextView android:id="@+id/text" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="aa" android:padding="10dp"/> </LinearLayout>
Adapter适配器
public class GoodsListAdapter extends RecyclerView.Adapter<GoodsListAdapter.GoodsHodler> { private List<Goods> mList = new ArrayList<>(); private Context context; public final static int LINEAR_TYPE = 0;//线性 public final static int GRID_TYPE = 1;//网格 private int viewType = LINEAR_TYPE; private OnItemClickListener onItemClickListener; public GoodsListAdapter(Context context) { this.context = context; } @Override public int getItemViewType(int position) { return viewType; } //设置item的视图类型 public void setViewType(int viewType) { this.viewType = viewType; } @NonNull @Override public GoodsHodler onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) { View view = null; if (viewType == LINEAR_TYPE) {//通过第二个参数viewType判断选用的视图 view = View.inflate(viewGroup.getContext(), R.layout.goods_linear_item, null);//加载item布局 } else { view = View.inflate(viewGroup.getContext(), R.layout.goods_grid_item, null);//加载item布局 } GoodsHodler goodsHodler = new GoodsHodler(view); return goodsHodler; } @Override public void onBindViewHolder(@NonNull GoodsHodler goodsHodler, int position) { final Goods goods = mList.get(position);//拿到商品,开始赋值 goodsHodler.itemView.setTag(mList.get(position)); //增加点击事件 goodsHodler.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context,WebActivity.class); intent.putExtra("url",goods.getDetailUrl()); context.startActivity(intent); // onItemClickListener.onItemClick(goods); } }); goodsHodler.text.setText(goods.getTitle()); //由于我们的数据图片提供的不标准,所以我们需要切割得到图片 String imageurl = "https" + goods.getImages().split("https")[1]; Log.i("dt", "imageUrl: " + imageurl); imageurl = imageurl.substring(0, imageurl.lastIndexOf(".jpg") + ".jpg".length()); Glide.with(context).load(imageurl).into(goodsHodler.imageView);//加载图片 } public static void main(String[] args) { String aa = "a111a222a333a"; String[] b = aa.split("a"); System.out.println(b[0]); } @Override public int getItemCount() { return mList.size(); } /** * 添加集合数据 */ public void addAll(List<Goods> data) { if (data != null) { mList.addAll(data); } } /** * 清空数据 */ public void clearList() { mList.clear(); } /** * 设置点击方法 */ public void setOnItemClickListener(OnItemClickListener onItemClickListener) { this.onItemClickListener = onItemClickListener; } class GoodsHodler extends RecyclerView.ViewHolder { TextView text; ImageView imageView; public GoodsHodler(@NonNull View itemView) { super(itemView); text = itemView.findViewById(R.id.text); imageView = itemView.findViewById(R.id.image); } } /** * @author dingtao * @date 2018/12/15 10:28 AM * 点击接口 */ public interface OnItemClickListener { void onItemClick(Goods goods); } }