一级购物车自定义View加减器、商品价格联动

首先肯定是要先用MVP进行展示,然后创建自定义view控件,自定义view布局一定要用RelativeLayout

<RelativeLayout
        android:id="@+id/layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tv_jian"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="-"
            android:textSize="16sp"
            android:padding="5dp"
            />

        <EditText
            android:id="@+id/ed_text"
            android:layout_width="60dp"
            android:layout_height="wrap_content"
            android:textSize="14sp"
            android:layout_toRightOf="@+id/tv_jian"
            android:inputType="number"
            />

        <TextView
            android:id="@+id/tv_jia"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/ed_text"
            android:text="+"
            android:textSize="16sp"
            android:padding="5dp"
            />
    </RelativeLayout>

连接布局进行一系列操作

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
/**
 * <p>文件描述:<p>
 * <p>作者:JYB<p>
 * <p>创建时间:2019/5/6<p>
 * <p>更改时间:2019/5/6<p>
 * <p>版本号:1<p>
 */
 //必须继承RelativeLayout 
public class ShopView extends RelativeLayout implements View.OnClickListener {

    private EditText editText;

    public ShopView(Context context) {
        super(context);
        //创建init方法
        init(context);
    }

    public ShopView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //创建init方法
        init(context);
    }
    //定义Context上下文
    private Context mContext;
    //生成方法,完善里面的操作
    private void init(Context context) {
        this.mContext=context;
        //获取布局
        View view =View.inflate(context,R.layout.layout_view,null);
        //获取控件
        editText = view.findViewById(R.id.ed_text);
        //设置点击事件
        view.findViewById(R.id.tv_jia).setOnClickListener(this);
        view.findViewById(R.id.tv_jian).setOnClickListener(this);
        //添加view
        addView(view);
    }

    @Override
    public void onClick(View v) {
        switc (v.getId()){
        	//加的点击方法
            case R.id.tv_jia:
            	//获取文本框
                String num = editText.getText().toString().trim();
                //将文本框设置为int类型
                int n = Integer.parseInt(num);
                //文本框加加
                n++;
                //通过接口回调获取总数
                mChangeNumListener.saleNum(n);
                //editText设置加的总数
                editText.setText(n+"");
                break;
                //减减的方法
            case R.id.tv_jian:
            	//获取文本框
                String numjian = editText.getText().toString().trim();
                //将文本框设置为int类型
                int njian = Integer.parseInt(numjian);
                //判断文本框==1,进行弹框提示
                if(njian==1){
                    Toast.makeText(mContext,"至少要有一个商品",Toast.LENGTH_SHORT).show();
                    //不要忘记return
                    return;
                }
                //实行减减的方法
                njian--;
                //通过接口回调获取总数
                mChangeNumListener.saleNum(njian);
                //edittext设置减的总数
                editText.setText(njian+"");
                break;
        }
    }
    public void setNum(int saleNum) {
        editText.setText(saleNum+"");
    }
    //创建接口回调的方法,最好见名识意
    private ChangeNumListener mChangeNumListener;
    public void setChangeNumListener(ChangeNumListener mChangeNumListener){
        this.mChangeNumListener = mChangeNumListener;
    }
    public interface ChangeNumListener{
        void saleNum(int saleNum);
    }
}

还需要在Adapter适配器里面进行一些操作

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
/**
 * <p>文件描述:<p>
 * <p>作者:JYB<p>
 * <p>创建时间:2019/5/6<p>
 * <p>更改时间:2019/5/6<p>
 * <p>版本号:1<p>
 */
public class UserAdapter extends XRecyclerView.Adapter<UserAdapter.ViewHolder> {
    private Context context;
    private List<UserBean.ResultBean> list = new ArrayList<>();

    public UserAdapter(Context context) {
        this.context = context;
    }

    public void setList(List<UserBean.ResultBean> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = View.inflate(context,R.layout.layout_adapter,null);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder viewHolder, final int i) {
        viewHolder.title.setText(list.get(i).getCommodityName());
        viewHolder.price.setText(list.get(i).getPrice()+"");
        viewHolder.simple.setImageURI(list.get(i).getMasterPic());
        //设置复选框的状态
        viewHolder.checkBox.setChecked(list.get(i).isCheck());
        //设置复选框点击事件
        viewHolder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            	//更改复选框的状态
                boolean ischecked = viewHolder.checkBox.isChecked();
                list.get(i).setCheck(ischecked);
                //通过接口回调将list传入展示页面
                mOnChangeDataListener.changeList(list);
            }
        });
        //设置数量的状态,并在ShopView进行赋值文本框
        viewHolder.shopView.setNum(list.get(i).getSaleNum());
        //获取ShopView接口回调的方法
        viewHolder.shopView.setChangeNumListener(new ShopView.ChangeNumListener() {
            @Override
            public void saleNum(int saleNum) {
            	//更改数量的状态
                list.get(i).setSaleNum(saleNum);
                //通过接口回调的方法将数量的list传入展示页面
                mOnChangeDataListener.changeList(list);
            }
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.simple)
        SimpleDraweeView simple;
        @BindView(R.id.title)
        TextView title;
        @BindView(R.id.price)
        TextView price;
        @BindView(R.id.checkBox)
        CheckBox checkBox;
        @BindView(R.id.shopview)
        ShopView shopView;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this,itemView);
        }
    }
    //创建接口回调的方法
    private OnChangeDataListener mOnChangeDataListener;
    public void setOnChangeDataListener(OnChangeDataListener mOnChangeDataListener){
        this.mOnChangeDataListener = mOnChangeDataListener;
    }
   public interface OnChangeDataListener{
        void changeList(List<UserBean.ResultBean> list);
   }
}

最后只需要在显示页面进行操作就完成了

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity implements LoadContract.lLoadView {

    @BindView(R.id.xrec)
    XRecyclerView mXrec;
    @BindView(R.id.checkBox1)
    CheckBox mCheckBox1;
    @BindView(R.id.price)
    TextView mPrice;
    @BindView(R.id.tv_num)
    TextView mTvNum;
    private LoadPresenter loadPresenter;
    private UserAdapter userAdapter;
    private List<UserBean.ResultBean> result1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        mXrec.setLayoutManager(new LinearLayoutManager(this));
        loadPresenter = new LoadPresenter(this);
        loadPresenter.getCart(new HashMap<String, String>());

        userAdapter = new UserAdapter(this);
        mXrec.setAdapter(userAdapter);
        //获取UserAdapter接口回调的方法
        userAdapter.setOnChangeDataListener(new UserAdapter.OnChangeDataListener() {
            @Override
            public void changeList(List<UserBean.ResultBean> list) {
            	//定义总价格
                float priceAll = 0;
                //定义总数量
                int countAll = 0;
                //定义初始值
                int num = 0;
                //for循环进行添加数据
                for (int i = 0; i < list.size(); i++) {
                	//判断选中状态
                    if (list.get(i).isCheck()) {
                    	//初始值加加
                        num++;
                        //获取价格
                        int price = list.get(i).getPrice();
                        //获取数量
                        int count = list.get(i).getSaleNum();
                        //总价=总价+价格*数量
                        priceAll = priceAll + price * count;
                        //总数量=总数量+数量
                        countAll = countAll + count;
                    }
                }
                //判断初始值==下标
                if (num == list.size()) {
                	//复选框选中
                    mCheckBox1.setChecked(true);
                } else {
                	//复选框不选中
                    mCheckBox1.setChecked(false);
                }
                //设置价格
                mPrice.setText(priceAll + "");
                //设置数量
                mTvNum.setText("去结算("+countAll+")");
            }
        });
        //设置复选框点击事件
        mCheckBox1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            	//获取复选框选中状态
                boolean ischecked = mCheckBox1.isChecked();
                //定义总价
                float priceAll = 0;
                //定义总数量
                int countAll = 0;
                //for循环进行添加数据
                for (int i = 0; i < result1.size(); i++) {
                	//更改复选框的状态
                    result1.get(i).setCheck(ischecked);
                    //获取价格
                    int price = result1.get(i).getPrice();
                    //获取数量
                    int count = result1.get(i).getSaleNum();
                    //总价格=总价格+价格*数量
                    priceAll = priceAll+price*count;
                    //总数量=总数量+数量
                    countAll = countAll+count;
                }
                //判断复选框为不选中
                if(!ischecked){
                	//总价为0
                    priceAll = 0;
                    //总数为0
                    countAll = 0;
                }
                //设置价格
                mPrice.setText(priceAll+"");
                //设置数量
                mTvNum.setText("去结算("+countAll+")");
                //再次加载数据
                userAdapter.setList(result1);
            }
        });
    }

    @Override
    public void Success(Object result) {
        UserBean userBean = (UserBean) result;
        result1 = userBean.getResult();
        userAdapter.setList(result1);
    }

    @Override
    public void Failure(Object msg) {

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现简单购物车加减商品结算,可以按照以下步骤进行: 1. 创建一个商品类,包含商品名称、商品价格、商品数量等属性。 ``` public class Goods { private String name; private double price; private int quantity; public Goods(String name, double price, int quantity) { this.name = name; this.price = price; this.quantity = quantity; } // getter和setter方法 } ``` 2. 在Activity中创建一个列表,用于展示购物车中的商品。 ``` List<Goods> goodsList = new ArrayList<>(); ``` 3. 创建一个适配器,将商品列表展示到RecyclerView中。 ``` public class GoodsAdapter extends RecyclerView.Adapter<GoodsAdapter.ViewHolder> { private List<Goods> mGoodsList; static class ViewHolder extends RecyclerView.ViewHolder { TextView goodsName; TextView goodsPrice; TextView goodsQuantity; public ViewHolder(View view) { super(view); goodsName = view.findViewById(R.id.goods_name); goodsPrice = view.findViewById(R.id.goods_price); goodsQuantity = view.findViewById(R.id.goods_quantity); } } public GoodsAdapter(List<Goods> goodsList) { mGoodsList = goodsList; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.goods_item, parent, false); ViewHolder holder = new ViewHolder(view); return holder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { Goods goods = mGoodsList.get(position); holder.goodsName.setText(goods.getName()); holder.goodsPrice.setText(String.valueOf(goods.getPrice())); holder.goodsQuantity.setText(String.valueOf(goods.getQuantity())); } @Override public int getItemCount() { return mGoodsList.size(); } } ``` 4. 在布局文件中添加RecyclerView和结算按钮。 ``` <androidx.recyclerview.widget.RecyclerView android:id="@+id/goods_list" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" /> <Button android:id="@+id/checkout_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="16dp" android:text="结算" /> ``` 5. 在Activity中初始化RecyclerView和适配器。 ``` RecyclerView recyclerView = findViewById(R.id.goods_list); LinearLayoutManager layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); GoodsAdapter adapter = new GoodsAdapter(goodsList); recyclerView.setAdapter(adapter); ``` 6. 添加添加商品和删除商品的功能。 ``` // 添加商品 goodsList.add(new Goods("商品1", 10.0, 1)); adapter.notifyDataSetChanged(); // 删除商品 goodsList.remove(position); adapter.notifyItemRemoved(position); ``` 7. 添加加减商品数量的功能。 ``` // 商品数量加1 goods.setQuantity(goods.getQuantity() + 1); adapter.notifyItemChanged(position); // 商品数量减1 if (goods.getQuantity() > 0) { goods.setQuantity(goods.getQuantity() - 1); adapter.notifyItemChanged(position); } ``` 8. 添加结算功能。 ``` double totalPrice = 0; for (Goods goods : goodsList) { totalPrice += goods.getPrice() * goods.getQuantity(); } Toast.makeText(this, "总价为:" + totalPrice, Toast.LENGTH_SHORT).show(); ``` 这样,一个简单的购物车加减商品结算就实现了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值