代码实现简单的购物车
程序员文章站
2022-07-05 23:29:51
build.gradle
apply plugin: 'com.android.application'
android {
compile...
build.gradle
apply plugin: 'com.android.application' android { compileSdkVersion 25 buildToolsVersion "26.0.2" defaultConfig { applicationId "gouwuche.bwei.com.gouwuche" minSdkVersion 15 targetSdkVersion 25 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:25.+' compile 'com.android.support:recyclerview-v7:25.3.1' compile 'com.squareup.okhttp3:okhttp:3.9.0' compile 'com.google.code.gson:gson:2.8.2' compile 'com.jakewharton:butterknife:8.8.1' compile 'com.jakewharton:butterknife-compiler:8.8.1' compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5' }
activity_main.xml
<!--?xml version="1.0" encoding="utf-8"?--> <linearlayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <linearlayout android:layout_weight="0" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:background="#FFFFFF" android:gravity="center_vertical" android:id="@+id/third_pay_linear"> <checkbox android:id="@+id/third_allselect" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginleft="@dimen/margin_10dp" android:text="全选" android:drawablepadding="@dimen/padding_5dp"> <linearlayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="vertical"> <textview android:id="@+id/third_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:textcolor="#000000" android:id="@+id/third_totalnum" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingleft="@dimen/padding_10dp" android:text="共0件商品" android:textsize="@dimen/common_font_size_14" android:paddingbottom="@dimen/padding_10dp"> </textview></textview></linearlayout> <textview android:id="@+id/third_submit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/login_btn" android:text="去结算" android:paddingleft="@dimen/margin_30dp" android:paddingright="@dimen/margin_30dp" android:paddingtop="@dimen/padding_10dp" android:paddingbottom="@dimen/padding_10dp" android:textcolor="#000000" android:layout_marginright="@dimen/margin_10dp"> </textview></checkbox></linearlayout> </android.support.v7.widget.recyclerview></linearlayout>
customview.xml
<!--?xml version="1.0" encoding="utf-8"?--> <linearlayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <button android:layout_width="10dp" android:layout_height="wrap_content" android:id="@+id/revserse" android:text="-" android:background="#00FFFFFF"> <edittext android:text="1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/content"> </edittext></button><button android:background="#00FFFFFF" android:text="+" android:id="@+id/add" android:layout_width="10dp" android:layout_height="wrap_content"> </button></linearlayout>
shop_adapter.xml
<!--?xml version="1.0" encoding="utf-8"?--> <relativelayout xmlns:android="https://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_margintop="20dp" android:layout_marginleft="20dp" android:layout_width="wrap_content" android:layout_height="wrap_content"> <imageview android:id="@+id/shopface" android:layout_width="80dp" android:layout_height="80dp" android:layout_marginleft="20dp" android:src="@mipmap/ic_launcher"> <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="30dp" android:layout_marginleft="20dp" android:id="@+id/danjia"> <gouwuche.bwei.com.gouwuche.customview android:id="@+id/customviewid" android:layout_margintop="20dp" android:layout_marginleft="20dp" android:layout_width="100dp" android:layout_height="50dp"> </gouwuche.bwei.com.gouwuche.customview></textview></imageview></checkbox></linearlayout> <button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginleft="20dp" android:layout_margintop="20dp" android:layout_alignparentright="true" android:id="@+id/shop_btn_del" android:text="删除"> </button></relativelayout>
ShopActivity
package gouwuche.bwei.com.gouwuche; import android.app.Activity; import android.os.Bundle; 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.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class ShopActivity extends Activity { @BindView(R.id.third_recyclerview) RecyclerView thirdRecyclerview; @BindView(R.id.third_allselect) CheckBox thirdAllselect; @BindView(R.id.third_totalprice) TextView thirdTotalprice; @BindView(R.id.third_totalnum) TextView thirdTotalnum; @BindView(R.id.third_submit) TextView thirdSubmit; @BindView(R.id.third_pay_linear) LinearLayout thirdPayLinear; private List mAllOrderList = new ArrayList<>(); private ShopAdapter adapter; private LinearLayoutManager manager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); getData(); // 1 为选中 2 选中 thirdAllselect.setTag(1); manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); adapter = new ShopAdapter(this); thirdRecyclerview.setLayoutManager(manager); thirdRecyclerview.setAdapter(adapter); adapter.add(mAllOrderList); adapter.setCheckBoxListener(new ShopAdapter.CheckBoxListener() { @Override public void check(int position, int count, boolean check, List list) { sum(list); } }); adapter.setCustomViewListener(new ShopAdapter.CustomViewListener() { @Override public void click(int count, List list) { sum(list); } }); adapter.setDelListener(new ShopAdapter.DelListener() { @Override public void del(int position, List list) { sum(list); } }); } float price = 0; int count; /** * 计算总价 * * @param mAllOrderList */ private void sum(List mAllOrderList) { 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; } } thirdTotalprice.setText("总价: " + price); thirdTotalnum.setText("共" + count + "件商品"); if (allCheck) { thirdAllselect.setTag(2); thirdAllselect.setChecked(true); // thirdAllselect.setBackgroundResource(R.drawable.shopcart_selected); } else { thirdAllselect.setTag(1); thirdAllselect.setChecked(false); // thirdAllselect.setBackgroundResource(R.drawable.shopcart_unselected); } } public void getData() { try { //模拟网络请求 InputStream inputStream = getAssets().open("shop.json"); String data = convertStreamToString(inputStream); 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(); } } public static String convertStreamToString(InputStream is) { /* * To convert the InputStream to String we use the BufferedReader.readLine() * method. We iterate until the BufferedReader return null which means * there's no more data to read. Each line will appended to a StringBuilder * and returned as String. */ BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } boolean select = false; @OnClick(R.id.third_allselect) public void onClick() { //全选按钮 点击事件 int tag = (Integer) thirdAllselect.getTag(); if (tag == 1) { thirdAllselect.setTag(2); select = true; } else { thirdAllselect.setTag(1); select = false; } for (ShopBean.OrderDataBean.CartlistBean bean : mAllOrderList) { bean.setCheck(select); } adapter.notifyDataSetChanged(); sum(adapter.getList()); } }
ShopAdapter
package gouwuche.bwei.com.gouwuche; import android.content.Context; import android.content.DialogInterface; import android.support.v7.app.AlertDialog; 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.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by muhanxi on 17/11/15. */ public class ShopAdapter extends RecyclerView.Adapter { private Context context; private List list ; public ShopAdapter(Context context) { this.context = context; } /** * 更新数据 * @param list */ public void add(List list){ if(this.list == null){ this.list = new ArrayList<>(); ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(context)); } this.list.addAll(list); notifyDataSetChanged(); } @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) { //防止checkbox 滑动 错乱 holder.checkbox.setChecked(list.get(position).isCheck()); holder.customviewid.setEditText(list.get(position).getCount()); holder.danjia.setText(list.get(position).getPrice()+""); ImageLoader.getInstance().displayImage(list.get(position).getDefaultPic(),holder.shopface); /** * checkbox 点击事件 */ 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.del.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new AlertDialog.Builder(context) .setTitle("是否确定删除" ) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { list.remove(position); notifyDataSetChanged(); } }) .setNegativeButton("取消" , null ) .show(); //list.remove(position); if(delListener != null){ delListener.del(position,list); } } }); } @Override public int getItemCount() { return list == null ? 0 : list.size(); } static class IViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.checkbox) CheckBox checkbox; @BindView(R.id.shopface) ImageView shopface; @BindView(R.id.danjia) TextView danjia; @BindView(R.id.customviewid) CustomView customviewid; @BindView(R.id.shop_btn_del) Button del ; IViewHolder(View view) { super(view); ButterKnife.bind(this, view); } } public List getList(){ return list; } CheckBoxListener checkBoxListener; /** * checkbox 点击事件 * @param listener */ public void setCheckBoxListener(CheckBoxListener listener){ this.checkBoxListener = listener; } interface CheckBoxListener { public void check(int position, int count, boolean check, List list); } CustomViewListener listener; /** * 加减号 点击事件 * @param listener */ public void setCustomViewListener(CustomViewListener listener){ this.listener = listener; } interface CustomViewListener { public void click(int count, List list); } DelListener delListener ; /** * 加减号 删除按钮事件 * @param listener */ public void setDelListener(DelListener listener) { this.delListener = listener ; } interface DelListener { public void del(int position, List list); } }
CustomView
package gouwuche.bwei.com.gouwuche; import android.content.Context; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; /** * Created by muhanxi on 17/11/15. */ public class CustomView extends LinearLayout { private EditText editText; private Button revserse; private Button add; private int mCount = 1 ; public CustomView(Context context) { super(context); } public CustomView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); View view = LayoutInflater.from(context).inflate(R.layout.customview,null,false); revserse = (Button) view.findViewById(R.id.revserse); add = (Button) view.findViewById(R.id.add); editText = (EditText) view.findViewById(R.id.content); revserse.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { //减号 try { String content = editText.getText().toString().trim() ; int count = Integer.valueOf(content)-1; if(count > 0){ editText.setText(count+""); mCount = count-1; if(listener != null){ listener.click(count); } } } catch (NumberFormatException 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 (NumberFormatException e) { e.printStackTrace(); } } }); addView(view); } public void setEditText(int count) { editText.setText(count+""); } public int getCurrentCount(){ return mCount ; } public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public ClickListener listener; public void setListener(ClickListener listener){ this.listener = listener; } /** * 加减号 点击事件 */ public interface ClickListener { public void click(int count); } }
ShopBean
assets里面要添加shop.json