Верните значения, чтобы начать - PullRequest
1 голос
/ 05 мая 2020

Если я нажму кнопку CHECKOUT, появится всплывающее окно. В этом всплывающем окне у вас есть возможность прервать транзакцию. Поэтому, если вы прервете транзакцию, все значения для предметов (французский огонь, вода, бургер) снова должны быть 0, как показано на рисунке ниже. Прямо сейчас, когда я прерываю транзакцию, значения остаются такими, какими я их настраивал раньше. Вы можете мне с этим помочь?

enter image description here

OrderActivity. java

package com.nfc.netvision;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Locale;

import static android.widget.Toast.*;

public class OrderActivity extends AppCompatActivity implements OrderAdapter.TotalListener {

    RecyclerView recyclerView;
    ArrayList<ModelOrder> orderArrayList;
    TextView textView_order_price;
    TextView textView_order_count;
    Dialog epicDialog;
    Button btnCheckout;
    Button btnAbort;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);

        recyclerView = findViewById(R.id.recyclerview_order_scroll);
        textView_order_price = findViewById(R.id.textView_order_price);
        textView_order_count = findViewById(R.id.textView_order_count);
        btnCheckout = (Button) findViewById(R.id.btnCheckout);


        orderArrayList = new ArrayList<>();
        orderArrayList.add(new ModelOrder(R.drawable.coke, "Coka Cola", "Eine Cola hält dich wach und schmeckt dazu.", "3",0));
        orderArrayList.add(new ModelOrder(R.drawable.fastfood, "Pommes", "Fritten für die Titten.", "5",0));
        orderArrayList.add(new ModelOrder(R.drawable.water, "Wasser", "Still und sanft, so mag ich es.", "5",0));
        orderArrayList.add(new ModelOrder(R.drawable.burger, "Burger", "Ach mir fällt nichts ein.", "10",0));

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        RecyclerView.LayoutManager recLiLayoutManager = layoutManager;

        recyclerView.setLayoutManager(recLiLayoutManager);

        OrderAdapter adapter = new OrderAdapter(this, orderArrayList, this);

        recyclerView.setAdapter(adapter);

        epicDialog = new Dialog(this);

        btnCheckout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showWaitingPopUp();


            }
        });



    }

    private void showWaitingPopUp() {
        epicDialog.setContentView(R.layout.order_popup_waiting);
        epicDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        btnAbort = (Button) epicDialog.findViewById(R.id.btnAbort);
        btnAbort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               epicDialog.dismiss();
            }
        });
        epicDialog.show();
    }


    @Override
    public void onTotalChanged(String result) {
        NumberFormat n = NumberFormat.getCurrencyInstance(Locale.GERMANY);
        textView_order_price.setText( n.format(Integer.parseInt(result)));
    }

    @Override
    public void onCountChanged(String result) {
        textView_order_count.setText(result);

    }
}

Адаптер заказа. java

package com.nfc.netvision;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;


import org.w3c.dom.Text;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Locale;


public class OrderAdapter extends RecyclerView.Adapter<OrderAdapter.ViewHolder> {

    private int totalAmount;
    private int totalItems;
    private Context mContext;
    private ArrayList<ModelOrder> nList;

    private TotalListener listener;

    interface TotalListener{
        void onTotalChanged(String result);
        void onCountChanged(String result);

    }
    OrderAdapter(Context context, ArrayList<ModelOrder> list, TotalListener listener) {
        mContext = context;
        nList = list;
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        LayoutInflater layoutInflater = LayoutInflater.from(mContext);
        View view = layoutInflater.inflate(R.layout.recyclerview_order_items, parent, false);

        ViewHolder viewHolder = new ViewHolder(view);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {

        final ModelOrder orderItem = nList.get(position);
        ImageView image = holder.item_image;
        final TextView name, place, price;
        name = holder.item_name;
        place = holder.item_place;
        price = holder.item_price;

        image.setImageResource(orderItem.getImage());

        name.setText(orderItem.getName());
        place.setText(orderItem.getPlace());
        price.setText(orderItem.getPrice());


        holder.order_item_minus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(orderItem.getCounter() > 0) {
                    orderItem.setCounter(orderItem.getCounter()-1);
                    holder.order_item_count.setText("" + orderItem.getCounter());
                    calculatePrice(Integer.parseInt((String) price.getText()), false);
                    countItems(orderItem.getCounter(), false);

                }

            }
        });

        holder.order_item_plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(orderItem.getCounter() < 9) {
                    orderItem.setCounter(orderItem.getCounter() + 1);
                    holder.order_item_count.setText("" + orderItem.getCounter());
                    calculatePrice(Integer.parseInt((String) price.getText()), true);
                    countItems(orderItem.getCounter(), true);
                }
            }
        });




    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {

        ImageView item_image;
        TextView item_name, item_place, item_price,order_item_minus,order_item_count, order_item_plus;

        public ViewHolder(@NonNull View itemView) {

            super(itemView);
            item_image = itemView.findViewById(R.id.order_item_image);
            item_name = itemView.findViewById(R.id.order_item_name);
            item_place = itemView.findViewById(R.id.order_item_place);
            item_price = itemView.findViewById(R.id.order_item_price);
            order_item_minus = itemView.findViewById(R.id.order_item_minus);
            order_item_plus = itemView.findViewById(R.id.order_item_plus);
            order_item_count = itemView.findViewById(R.id.order_item_count);
        }
    }

    private void calculatePrice(int pPrice, boolean pUpDown) {
        if(pUpDown) {
            totalAmount = totalAmount + pPrice;
        }
        else {
            totalAmount = totalAmount - pPrice;
        }

        listener.onTotalChanged(totalAmount+ "");
    }

    private void countItems(int pCounter, boolean pUpDown){
        if (pUpDown){
            totalItems = totalItems + 1;
        }
        else{
            totalItems = totalItems - 1;
        }
        listener.onCountChanged(totalItems+ "");

    }


}

1 Ответ

0 голосов

Они остаются прежними, потому что внутри onClick кнопки прерывания вы просто закрываете диалоговое окно и не меняете значения списка.

Я предлагаю выполнить итерацию по списку и установить все счетчики на 0.

Также не забудьте уведомить RecyclerView о том, что вы что-то изменили, в этом случае вы сбрасываете все счетчики на 0. В противном случае вы не увидите изменений в своем приложении.

private void showWaitingPopUp() {
    epicDialog.setContentView(R.layout.order_popup_waiting);
    epicDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    btnAbort = epicDialog.findViewById(R.id.btnAbort);
    btnAbort.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            // Set all orders count to 0
            for (ModelOrder modelOrder: orderArrayList) {
                modelOrder.setCounter(0);
            }
            // Notify RecyclerView about the changes
            adapter.notifyDataSetChanged();

            epicDialog.dismiss();
        }
    });
    epicDialog.show();
}

Я заметил, что у вас не было адаптера в качестве глобальной переменной, поэтому объявите его так:

public class OrderActivity extends AppCompatActivity implements OrderAdapter.TotalListener {

    // other variables

    // Change adapter variable to global
    OrderAdapter adapter;

    // ...



Примечания на стороне: Я также заметил, что вы дважды передали свою активность внутри конструктора OrderAdapter.

OrderAdapter adapter = new OrderAdapter(this, orderArrayList, this);

Вы можете просто сделать:

OrderAdapter adapter = new OrderAdapter(this, orderArrayList);

Затем внутри вашего конструктора:

OrderAdapter(Context context, ArrayList<ModelOrder> list) {
    mContext = context;
    nList = list;

    // You can simply cast the context to the listener
    listener = (TotalListener) context;
}



Надеюсь, мой ответ поможет, удачного кодирования!


Изменить: я переместил свои ответы на другие вопросы OP в чате.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...