一级购物车
话不多说,先实现一个一级列表购物车
在main文件夹下创建一个文件夹assets里创建shop.json文件,把从网上获取的数据复制进去,也可以自己在android的java的代码进行解析,获取网络数据即可。
依赖如下:
这是imageloader依赖
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
这是gson解析的依赖 compile 'com.google.code.gson:gson:2.8.2'
这是recyclerView列表的依赖 compile 'com.github.liuguangqiang.SuperRecyclerView:super-recyclerview:0.1.2'
这是butterknife依赖 compile 'com.jakewharton:butterknife:7.0.0'
效果如下:
这是shopactivity页面的布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="mvpframework.bwie.com.shop.ShopActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerview" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"></android.support.v7.widget.RecyclerView> <LinearLayout android:id="@+id/pay_linear" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_weight="0" android:background="#FFFFFF" android:orientation="horizontal"> <CheckBox android:id="@+id/allselect" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/margin_10dp" android:drawableLeft="@drawable/shopcart_add_btn" android:drawablePadding="@dimen/padding_5dp" android:text="全选"/> <LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="vertical"> <TextView android:id="@+id/totalprice" android:layout_width="200dp" android:layout_height="wrap_content" android:paddingLeft="@dimen/padding_10dp" android:paddingTop="@dimen/padding_10dp" android:text="总价:" android:textColor="#000000" android:textSize="@dimen/common_font_size_16"/> <TextView android:id="@+id/totalnum" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="@dimen/padding_10dp" android:text="共0件商品" android:textColor="#000000" android:textSize="@dimen/padding_10dp"/> </LinearLayout> <TextView android:id="@+id/submit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="@dimen/margin_10dp" android:background="@drawable/login_btn" android:paddingBottom="@dimen/padding_10dp" android:paddingLeft="@dimen/margin_30dp" android:paddingRight="@dimen/margin_30dp" android:paddingTop="@dimen/padding_10dp" android:text="去结算" android:textColor="#000000"/> </LinearLayout> </LinearLayout>
这是customview页面的是布局
<?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"> <Button android:id="@+id/revserse" android:layout_width="10dp" android:layout_height="wrap_content" android:background="#00FFFF" android:text="-"/> <EditText android:id="@+id/content" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="1"/> <Button android:id="@+id/add" android:layout_width="10dp" android:layout_height="wrap_content" android:background="#00ffff" android:text="+"/> </LinearLayout>
这是adapter布局的代码
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <CheckBox android:id="@+id/checkbox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_marginTop="20dp"/> <ImageView android:id="@+id/shopface" android:layout_width="80dp" android:layout_height="80dp" android:layout_marginLeft="20dp" android:src="@mipmap/ic_launcher"/> <TextView android:id="@+id/danjia" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_marginTop="30dp"/> <mvpframework.bwie.com.shop.CustomView android:id="@+id/customviewid" android:layout_width="100dp" android:layout_height="50dp" android:layout_marginLeft="20dp" android:layout_marginTop="20dp"/> </LinearLayout> <Button android:id="@+id/shop_btn_del" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_marginLeft="20dp" android:layout_marginTop="20dp" android:text="删除"/> </RelativeLayout>
下面才是java代码
这是shopactivity的代码
package mvpframework.bwie.com.shop; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.TextView; import com.google.gson.Gson; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; public class ShopActivity extends AppCompatActivity { @Bind(R.id.recyclerview) RecyclerView recyclerview; @Bind(R.id.allselect) CheckBox allselect; @Bind(R.id.totalprice) TextView totalprice; @Bind(R.id.totalnum) TextView totalnum; @Bind(R.id.submit) TextView submit; @Bind(R.id.pay_linear) LinearLayout payLinear; private List<ShopBean.OrderDataBean.CartlistBean> mAllOrderList = new ArrayList<>(); private ShopAdapter adapter; private LinearLayoutManager manager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_shop); ButterKnife.bind(this); getData(); allselect.setTag(1); manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); adapter = new ShopAdapter(this); recyclerview.setLayoutManager(manager); recyclerview.setAdapter(adapter); adapter.add(mAllOrderList); adapter.setCheckBoxListener(new ShopAdapter.CheckBoxListener() { @Override public void check(int position, int count, boolean check, List<ShopBean.OrderDataBean.CartlistBean> list) { sum(list); } }); adapter.setCustomViewListener(new ShopAdapter.CustomViewListener() { @Override public void click(int count, List<ShopBean.OrderDataBean.CartlistBean> list) { sum(list); } }); adapter.setDelListener(new ShopAdapter.DelListener() { @Override public void del(int position, List<ShopBean.OrderDataBean.CartlistBean> list) { sum(list); } }); } float price = 0; int count; private void sum(List<ShopBean.OrderDataBean.CartlistBean> mAllOrderList) { //刚开始把数据化为0 price = 0; count = 0; boolean allCheck = true; for (ShopBean.OrderDataBean.CartlistBean bean : mAllOrderList) { if (bean.isCheck()) { price += bean.getPrice() * bean.getCount(); count += bean.getCount(); } else { allCheck = false; } } //总价价格 totalprice.setText("总价:" + price); //总数量 totalnum.setText("共:" + count + "件商品"); //判断点击 if (allCheck) { allselect.setTag(2); allselect.setChecked(true); } else { allselect.setTag(1); allselect.setChecked(false); } } //gson解析 private void getData() { try { InputStream inputStream = getAssets().open("shop.json"); String data = convertStreamToString(inputStream, "utf-8"); Gson gson = new Gson(); ShopBean shopBean = gson.fromJson(data, ShopBean.class); for (int i = 0; i < shopBean.getOrderData().size(); i++) { int length = shopBean.getOrderData().get(i).getCartlist().size(); for (int j = 0; j < length; j++) { mAllOrderList.add(shopBean.getOrderData().get(i).getCartlist().get(j)); } } } catch (Exception e) { e.printStackTrace(); } } private String convertStreamToString(InputStream inputStream, String s) { try { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuilder builder = new StringBuilder(); String line = null; while ((line = bufferedReader.readLine()) != null) { builder.append(line); } bufferedReader.close(); return builder.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } //默认为没选中 boolean select = false; //全选点击事件 @OnClick(R.id.allselect) public void onClick() { int tag = (Integer) allselect.getTag(); //未点击为1 点击为2 if (tag == 1) { allselect.setTag(2); select = true; } else { allselect.setTag(1); select = false; } //全选把数据全都加起来 for (ShopBean.OrderDataBean.CartlistBean bean : mAllOrderList) { bean.setCheck(select); } //适配器刷新 adapter.notifyDataSetChanged(); sum(adapter.getList()); } }
这是customview的代码
package mvpframework.bwie.com.shop; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import butterknife.Bind; import butterknife.ButterKnife; /** * Created by CZ on 2017/11/17. */ public class CustomView extends LinearLayout { @Bind(R.id.revserse) Button revserse; @Bind(R.id.content) EditText editText; @Bind(R.id.add) Button add; private int mCount = 1; public ClickListener listener; public CustomView(Context context) { super(context); } public CustomView(final Context context, AttributeSet attrs) { super(context, attrs); //布局规划 View view = LayoutInflater.from(context).inflate(R.layout.customview, null, false); ButterKnife.bind(this, view); //减号点击 revserse.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { try { //点击减号的还剩下几个数在文本框显示 String content = editText.getText().toString().trim(); int count = Integer.valueOf(content); //判断是否大于1如果等于1则不在减 if (count > 1) { mCount = count - 1; editText.setText(mCount + ""); if (listener != null) { listener.click(mCount); } } } catch (Exception e) { e.printStackTrace(); } } }); //加号点击事件 add.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { try { //点击后加一个数 String content = editText.getText().toString().trim(); int count = Integer.valueOf(content) + 1; mCount = count; editText.setText(count + ""); if (listener != null) { listener.click(count); } } catch (Exception e) { e.printStackTrace(); } } }); addView(view); } //文本框显示数字 public void setEditText(int count){ editText.setText(count+""); } public CustomView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public void setListener(ClickListener listener) { this.listener = listener; } public int getCurrentCount() { return mCount; } public interface ClickListener { public void click(int count); } }
这是adapter代码
package mvpframework.bwie.com.shop; import android.content.Context; import android.graphics.Bitmap; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.ImageScaleType; import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer; import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; /** * Created by CZ on 2017/11/17. */ public class ShopAdapter extends RecyclerView.Adapter<ShopAdapter.IViewHolder> { private Context context; private List<ShopBean.OrderDataBean.CartlistBean> list; public ShopAdapter(Context context) { this.context = context; } public void add(List<ShopBean.OrderDataBean.CartlistBean> list) { if (this.list == null) { this.list = new ArrayList<>(); } this.list.addAll(list); notifyDataSetChanged(); ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(context)); } @Override public IViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = View.inflate(context, R.layout.shop_adapter, null); return new IViewHolder(view); } @Override public void onBindViewHolder(final IViewHolder holder, final int position) { holder.checkbox.setChecked(list.get(position).isCheck()); holder.danjia.setText(list.get(position).getPrice() + ""); holder.customviewid.setEditText(list.get(position).getCount()); ImageLoader.getInstance().displayImage(list.get(position).getDefaultPic(), holder.shopface, getOption()); //多选框判断 holder.checkbox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { list.get(position).setCheck(holder.checkbox.isChecked()); notifyDataSetChanged(); if (checkBoxListener != null) { checkBoxListener.check(position, holder.customviewid.getCurrentCount(), holder.checkbox.isChecked(), list); } } }); holder.customviewid.setListener(new CustomView.ClickListener() { @Override public void click(int count) { list.get(position).setCount(count); notifyDataSetChanged(); if (listener != null) { listener.click(count, list); } } }); //删除 holder.shopBtnDel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { list.remove(position); notifyDataSetChanged(); if (delListener != null) { delListener.del(position, list); } } }); } @Override public int getItemCount() { return list == null ? 0 : list.size(); } //控件 public class IViewHolder extends RecyclerView.ViewHolder { @Bind(R.id.checkbox) CheckBox checkbox; @Bind(R.id.shopface) ImageView shopface; @Bind(R.id.danjia) TextView danjia; @Bind(R.id.customviewid) CustomView customviewid; @Bind(R.id.shop_btn_del) Button shopBtnDel; public IViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } //数据 public List<ShopBean.OrderDataBean.CartlistBean> getList() { return list; } CheckBoxListener checkBoxListener; //多选框 public void setCheckBoxListener(CheckBoxListener listener) { this.checkBoxListener = listener; } interface CheckBoxListener { public void check(int position, int count, boolean check, List<ShopBean.OrderDataBean.CartlistBean> list); } CustomViewListener listener; //另外一个页面的数据 public void setCustomViewListener(CustomViewListener listener) { this.listener = listener; } interface CustomViewListener { public void click(int count, List<ShopBean.OrderDataBean.CartlistBean> list); } DelListener delListener; /** * 加减号 删除按钮事件 * * @param listener */ public void setDelListener(DelListener listener) { this.delListener = listener; } interface DelListener { public void del(int position, List<ShopBean.OrderDataBean.CartlistBean> list); } //imageloader两个参数 public DisplayImageOptions getOption() { DisplayImageOptions options = new DisplayImageOptions.Builder() .showImageOnLoading(R.mipmap.ic_launcher) //设置图片在下载期间显示的图片 .showImageForEmptyUri(R.mipmap.ic_launcher)//设置图的时片Uri为空或是错误候显示的图片 .showImageOnFail(R.mipmap.ic_launcher) //设置图片加载/解码过程中错误时候显示的图片 .cacheInMemory(true)//设置下载的图片是否缓存在内存中 .cacheOnDisk(true)//设置下载的图片是否缓存在SD卡中 .considerExifParams(true) //是否考虑JPEG图像EXIF参数(旋转,翻转) .imageScaleType(ImageScaleType.IN_SAMPLE_INT)//设置图片以如何的编码方式显示 .bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型 //.decodingOptions(BitmapFactory.Options decodingOptions)//设置图片的解码配置 .delayBeforeLoading(0)//int delayInMillis为你设置的下载前的延迟时间 //设置图片加入缓存前,对bitmap进行设置 //.preProcessor(BitmapProcessor preProcessor) .resetViewBeforeLoading(true)//设置图片在下载前是否重置,复位 .displayer(new RoundedBitmapDisplayer(20))//不推荐用!!!!是否设置为圆角,弧度为多少 .displayer(new FadeInBitmapDisplayer(100))//是否图片加载好后渐入的动画时间,可能会出现闪动 .build();//构建完成 return options; } }
还得再drawable文件夹里创建一个文件login_btn
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <corners android:radius="@dimen/height_200dp"></corners> <solid android:color="@color/pressed_icon_color"></solid> </shape>
在创建一个shopcart_add_btn文件
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <corners android:radius="@dimen/height_200dp"></corners> <stroke android:color="@color/background_color" android:width="1dp"></stroke> </shape>
还得在colors添加代码
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#3F51B5</color> <color name="colorPrimaryDark">#303F9F</color> <color name="colorAccent">#FF4081</color> <color name="cwhite">#FFFFFF</color> <color name="title_bg">#FDE23D</color> <color name="tab_bg">#FFFFFF</color> <color name="tab_normal_textcolor">#373737</color> <color name="tab_selected_textcolor">#FDE23D</color> <color name="coffer">#442509</color> <color name="pressed_icon_color">#e53e42</color> <color name="background_color">#f6f6f6</color> <color name="main_red_text">#e53e42</color> <dimen name="padding_20dp">20dp</dimen> <color name="splitline_color">#dddddd</color> <color name="cblack">#000000</color> </resources>
在dimens添加代码
<resources> <dimen name="margin_10dp">10dp</dimen> <dimen name="padding_5dp">5dp</dimen> <dimen name="padding_10dp">10dp</dimen> <dimen name="common_font_size_16">16sp</dimen> <dimen name="common_font_size_14">14sp</dimen> <dimen name="height_200dp">200dp</dimen> <dimen name="margin_30dp">30dp</dimen> <dimen name="margin_15dp">15dp</dimen> <dimen name="margin_1dp">1dp</dimen> <dimen name="margin_5dp">5dp</dimen> <dimen name="common_font_size_12">12sp</dimen> <dimen name="padding_2dp">2dp</dimen> <dimen name="margin_20dp">20dp</dimen> </resources>
这是bean类,可以用来参考一下
package mvpframework.bwie.com.shop; import java.util.List; /** * Created by muhanxi on 17/6/21. */ public class ShopBean { /** * code : 200 * orderData : [{"shopId":1,"shopName":"京东自营","cartlist":[{"id":1,"shopId":1,"shopName":"京东自营","defaultPic":"https://img30.360buyimg.com/popWareDetail/jfs/t3208/194/7616404169/244198/369625db/58b7d093N03520fb7.jpg","productId":1,"productName":"三只松鼠_零食大礼包","color":null,"size":null,"price":20,"count":2},{"id":2,"shopId":1,"shopName":"京东自营","defaultPic":"https://img14.360buyimg.com/n0/jfs/t2971/15/167732091/93002/204c1016/574d9d9aNe4e6fa7a.jpg","productId":2,"productName":null,"color":null,"size":null,"price":148,"count":3}]},{"shopId":2,"shopName":"海澜之家","cartlist":[{"id":1,"shopId":2,"shopName":"海澜之家","defaultPic":"https://img30.360buyimg.com/popWaterMark/jfs/t4075/83/1343091204/132469/9034cb9c/5873496bN68020ba8.jpg","productId":1,"productName":"短袖T恤男 2017夏季新品","color":null,"size":null,"price":181,"count":1}]}] */ private int code; private List<OrderDataBean> orderData; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public List<OrderDataBean> getOrderData() { return orderData; } public void setOrderData(List<OrderDataBean> orderData) { this.orderData = orderData; } public static class OrderDataBean { /** * shopId : 1 * shopName : 京东自营 * cartlist : [{"id":1,"shopId":1,"shopName":"京东自营","defaultPic":"https://img30.360buyimg.com/popWareDetail/jfs/t3208/194/7616404169/244198/369625db/58b7d093N03520fb7.jpg","productId":1,"productName":"三只松鼠_零食大礼包","color":null,"size":null,"price":20,"count":2},{"id":2,"shopId":1,"shopName":"京东自营","defaultPic":"https://img14.360buyimg.com/n0/jfs/t2971/15/167732091/93002/204c1016/574d9d9aNe4e6fa7a.jpg","productId":2,"productName":null,"color":null,"size":null,"price":148,"count":3}] */ private int shopId; private String shopName; private List<CartlistBean> cartlist; public int getShopId() { return shopId; } public void setShopId(int shopId) { this.shopId = shopId; } public String getShopName() { return shopName; } public void setShopName(String shopName) { this.shopName = shopName; } public List<CartlistBean> getCartlist() { return cartlist; } public void setCartlist(List<CartlistBean> cartlist) { this.cartlist = cartlist; } public static class CartlistBean { /** * id : 1 * shopId : 1 * shopName : 京东自营 * defaultPic : https://img30.360buyimg.com/popWareDetail/jfs/t3208/194/7616404169/244198/369625db/58b7d093N03520fb7.jpg * productId : 1 * productName : 三只松鼠_零食大礼包 * color : null * size : null * price : 20 * count : 2 */ private int id; private int shopId; private String shopName; private String defaultPic; private int productId; private String productName; private Object color; private Object size; private int price; private int count; private boolean check; //商品是否被选中 private boolean isSelect = true; //是否是第一个 如果isfirst 等于1 显示商户的名称, 否则隐藏商户的名称 private int isFirst = 2; //商户是否被选中 private boolean isShopSelect = true; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getShopId() { return shopId; } public void setShopId(int shopId) { this.shopId = shopId; } public String getShopName() { return shopName; } public void setShopName(String shopName) { this.shopName = shopName; } public String getDefaultPic() { return defaultPic; } public void setDefaultPic(String defaultPic) { this.defaultPic = defaultPic; } public int getProductId() { return productId; } public void setProductId(int productId) { this.productId = productId; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public Object getColor() { return color; } public void setColor(Object color) { this.color = color; } public Object getSize() { return size; } public void setSize(Object size) { this.size = size; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public boolean isSelect() { return isSelect; } public void setSelect(boolean select) { isSelect = select; } public int getIsFirst() { return isFirst; } public void setIsFirst(int isFirst) { this.isFirst = isFirst; } public boolean isShopSelect() { return isShopSelect; } public void setShopSelect(boolean shopSelect) { isShopSelect = shopSelect; } public boolean isCheck() { return check; } public void setCheck(boolean check) { this.check = check; } } } }