一级购物车

来源:互联网 发布:游戏代练网站源码 编辑:程序博客网 时间:2024/04/20 03:24

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="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:layout_width="match_parent"    android:layout_height="match_parent">    <android.support.v7.widget.RecyclerView        android:id="@+id/third_recyclerview"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="1"        />    <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"                />        </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"            />    </LinearLayout></LinearLayout>

customview.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">    <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"/>    <Button        android:background="#00FFFFFF"        android:text="+"        android:id="@+id/add"        android:layout_width="10dp"        android:layout_height="wrap_content"        /></LinearLayout>

shop_adapter.xml

<?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_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"/>    </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="删除"/></RelativeLayout>

colors.xml

<?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>

dimens

<resources><!-- Default screen margins, per the Android Design guidelines. --><dimen name="activity_horizontal_margin">16dp</dimen><dimen name="activity_vertical_margin">16dp</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_10dp">10dp</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>

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<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_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<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;    /**     * 计算总价     *     * @param mAllOrderList     */    private void sum(List<ShopBean.OrderDataBean.CartlistBean> 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<ShopAdapter.IViewHolder> {    private Context context;    private List<ShopBean.OrderDataBean.CartlistBean> list ;    public ShopAdapter(Context context) {        this.context = context;    }    /**     * 更新数据     * @param list     */    public void add(List<ShopBean.OrderDataBean.CartlistBean> 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<ShopBean.OrderDataBean.CartlistBean> 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<ShopBean.OrderDataBean.CartlistBean> list);    }     CustomViewListener listener;    /**     * 加减号 点击事件     * @param 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);    }}

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

原创粉丝点击