计算recyclerview中项目列表中项目的总价格

时间:2017-03-16 09:32:51

标签: android for-loop android-recyclerview recycler-adapter android-sharedpreferences

我想计算列表中商品的价格,并将值存储在sharedpreference中。每个项目的价格都采用双重形式。问题是当我使用我的方法时,它只考虑列表中的一个项目并计算该值。我使用NumberPicker来更改商品的数量。

这是我的适配器,用于处理将在RecyclerView上显示的项目列表:

public class CartAdapter extends RecyclerView.Adapter<CartAdapter.ViewHolder> {
    private List<SingleItem> items;
    private SessionManager sessionManager;
    private Context context;
    private int pos;

    public CartAdapter() {
    }

    public CartAdapter(Context context, List<SingleItem> items) {
        this.items = items;
        this.context = context;
        sessionManager = new SessionManager(context);

    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cartitem, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        final SingleItem singleItem = items.get(position);
        holder.tv_title.setText(singleItem.getTitle());
        holder.tv_price.setText("Ksh: " + singleItem.getPrice());
        Picasso.with(context).load(singleItem.getUrl()).fit().into(holder.imgcart);
        holder.numcart.setMinValue(1);
        holder.numcart.setMaxValue(15);
        holder.numcart.setWrapSelectorWheel(false);
        int qty = holder.numcart.getValue();
        getTotal(qty, singleItem.getPrice());
    }

    public double getTotal(int value, double amount){

        double totalamount;
        double amountall = amount;
        int quantity = value;
        totalamount = amountall * quantity;
        sessionManager.grandtotal("Ksh: " + totalamount);
        return totalamount;
    }


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

    public void removeItem(SingleItem item) {
        sessionManager.removeitem(context,item);
        items.remove(item);
        notifyDataSetChanged();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView tv_price;
        TextView tv_title;
        NumberPicker numcart;
        ImageView imgcart;

        public ViewHolder(View view) {
            super(view);

            tv_price = (TextView) view.findViewById(R.id.titlecart);
            tv_title = (TextView) view.findViewById(R.id.pricecart);
            numcart = (NumberPicker) view.findViewById(R.id.pickercart);
            imgcart = (ImageView) view.findViewById(R.id.imgcart);
        }
    }
}

以下是我在片段上显示RecyclerView的方法:

public class Details extends Fragment {
    private RecyclerView RecyclerDetails;
    private TextView CartPrice;
    private CheckBox CheckCart;
    private List<SingleItem> list;
    private CartAdapter adapter;
    private boolean add = false;
    private Paint p = new Paint();
    private SessionManager sessionManager;
    private int pos;



    public Details() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_details, container, false);

        RecyclerDetails = (RecyclerView) view.findViewById(R.id.recyclercart);
        CartPrice = (TextView) view.findViewById(R.id.tvcarttotal);
        CheckCart = (CheckBox) view.findViewById(R.id.chkcart);

        sessionManager = new SessionManager(getContext());

        Toasty.info(getContext(),"Swipe to go to Next", Toast.LENGTH_SHORT,true).show();

        RecyclerDetails.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        RecyclerDetails.setLayoutManager(layoutManager);

        list = sessionManager.getItems(getContext());

        HashMap<String,String> map = sessionManager.itemstostring();
        String data = map.get(SessionManager.KEY_ITEMS);
        Log.i(Constants.TAG,data);

        HashMap<String,String> tot = sessionManager.getgrandtotal();
        String total = tot.get(SessionManager.KEY_TOTAL);

        CartPrice.setText(total);

       CheckCart.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               if (((CheckBox) v).isChecked()){
                   sessionManager.saveditems("true");
               } else {
                   sessionManager.saveditems("false");
               }
           }
       });

        RecyclerDetails.addOnItemTouchListener(new RecyclerItemClickListener(getContext(), new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        }));


        if(list != null){
            adapter = new CartAdapter(getContext(),list);
            RecyclerDetails.setAdapter(adapter);
            }

        initswipe();
        return view;
    }

    private void initswipe() {
        ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) {

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                int position = viewHolder.getAdapterPosition();

                if (direction == ItemTouchHelper.RIGHT) {
                    adapter.removeItem(list.get(position));
                    sessionManager.saveitems(getContext(),list);

                }

            }

            @Override
            public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {

                Bitmap icon;
                if(actionState == ItemTouchHelper.ACTION_STATE_SWIPE){

                    View itemView = viewHolder.itemView;
                    float height = (float) itemView.getBottom() - (float) itemView.getTop();
                    float width = height / 3;

                    if(dX > 0){
                        p.setColor(Color.parseColor("#14a895"));
                        RectF background = new RectF((float) itemView.getLeft(), (float) itemView.getTop(), dX,(float) itemView.getBottom());
                        c.drawRect(background,p);
                        icon = BitmapFactory.decodeResource(getResources(), android.R.drawable.ic_menu_delete);
                        RectF icon_dest = new RectF((float) itemView.getLeft() + width ,(float) itemView.getTop() + width,(float) itemView.getLeft()+ 2*width,(float)itemView.getBottom() - width);
                        c.drawBitmap(icon,null,icon_dest,p);
                    } else {
                        p.setColor(Color.parseColor("#14a895"));
                        RectF background = new RectF((float) itemView.getRight() + dX, (float) itemView.getTop(),(float) itemView.getRight(), (float) itemView.getBottom());
                        c.drawRect(background,p);
                        icon = BitmapFactory.decodeResource(getResources(),android.R.drawable.ic_menu_delete);
                        RectF icon_dest = new RectF((float) itemView.getRight() - 2*width ,(float) itemView.getTop() + width,(float) itemView.getRight() - width,(float)itemView.getBottom() - width);
                        c.drawBitmap(icon,null,icon_dest,p);
                    }
                }
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
            }
        };
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
        itemTouchHelper.attachToRecyclerView(RecyclerDetails);
    }

}

最后,这是我用来存储列表中所有项目总数的值的函数

public void grandtotal (String total){
        editor.putString(KEY_TOTAL,total);
        editor.commit();
    }

    public HashMap<String, String> getgrandtotal(){
        HashMap<String, String> tot = new HashMap<>();
        tot.put(KEY_TOTAL,pref.getString(KEY_TOTAL,null));
        return tot;
    }

我是否有一个函数我没有包含在我正在显示RecyclerView项目的片段中?

只需要进行一些小改动吗?

2 个答案:

答案 0 :(得分:2)

private int grandTotal(List<SingleItem> items){

int totalPrice = 0;
for(int i = 0 ; i < items.size(); i++) {
    totalPrice += items.get(i).getPrice(); 
}

return totalPrice;
}

这是您需要实施以获得总价的方法。当您添加项目或从列表中删除项目时,U可以调用此方法。

答案 1 :(得分:0)

kotlin中的此功能

var total = 0;
            for ( i in 0 until  myDebt.size){
                total += myDebt[i].valueAdp
            }

这是您需要获得总价的方法。可以在您的活动中调用此方法 并且您仍然可以将值分配给textView。

 mtv_my_debt.setText(String.valueOf(total))