我需要执行add-to-cart功能,可以选择增加或减少商品的数量

mcdcgff0  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(432)

产品数量更改按钮,但当我单击添加到购物车按钮并将可见性更改为gone others+,-按钮可见性更改为屏幕上显示的visible时,我单击这两个按钮中的任何一个,它们的侦听器都不工作,重新启动应用程序后,两个+,-按钮都开始正常工作。还有一件事,我需要我的通知徽章价值不应该改变,如果一个产品已经在购物车,然后改变其数量,但在我的情况下,价值变化,如果我增加数量或减少数量的产品。提前谢谢
家庭碎片

package colon.semi.com.dealMall.fragments;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.smarteist.autoimageslider.SliderAnimations;
import com.smarteist.autoimageslider.SliderView;
import java.util.ArrayList;
import java.util.List;
import colon.semi.com.dealMall.R;
import colon.semi.com.dealMall.Utils.AppClass;
import colon.semi.com.dealMall.Utils.Constants;
import colon.semi.com.dealMall.adapters.DealsSliderAdapter;
import colon.semi.com.dealMall.adapters.DevicesParentRecyclerAdapter;
import colon.semi.com.dealMall.adapters.SliderAdapterExample;
import colon.semi.com.dealMall.adapters.TopSellingAdapter;
import colon.semi.com.dealMall.dataModels.CartDataTable;
import colon.semi.com.dealMall.dataModels.CartResponse;
import colon.semi.com.dealMall.dataModels.HomeDataModel;
import colon.semi.com.dealMall.dataModels.ImagesListDM;
import colon.semi.com.dealMall.dataModels.Points;
import colon.semi.com.dealMall.dataModels.Product;
import colon.semi.com.dealMall.dataModels.SliderImagesResponse;
import colon.semi.com.dealMall.dataModels.TopSellingResponse;
import colon.semi.com.dealMall.viewModels.CartViewModel;
import colon.semi.com.dealMall.viewModels.HomeFragmentViewModel;
import colon.semi.com.dealMall.viewModels.PointsViewModel;

public class HomeFragment extends Fragment {

    HomeFragmentViewModel homeFragmentViewModel;

    View view;

    SliderView sliderView;
    SliderView imageSliderDeals;

    RecyclerView recyclerView;
    private ArrayList<String> listTitleRecycler = new ArrayList<>();

    DevicesParentRecyclerAdapter homeParentRecyclerAdapter;

    boolean topSellingComplete = false;
    boolean latestComplete = false;
    boolean allproductsComplete = false;

    HomeDataModel homeDataModel = new HomeDataModel();
    CartViewModel cartViewModel;

    ProgressDialog progressDialog;

    RecyclerView recylerTimeDeal;
    TopSellingAdapter timeDealAdapter;

    int[] imgResLounge = {R.drawable.ic_get_free, R.drawable.ic_seasonal_deals, 
    R.drawable.ic_grocery_deals,
            R.drawable.ic_stationary_deals};
    //CategoryNames
    String[] imgNamesLounge = {"Men\nLounge", "Women\nLounge", "Cosmetic\nLounge", "Garments\nLounge"};

    //Liststudent ERP OBJECT
    ArrayList<ImagesListDM> loungeList = new ArrayList<>();
    SharedPreferences sharedPreferences;
    private TextView totalPointsTextView;
    private TextView totalPrice;
    private PointsViewModel pointsViewModel;

    private View viewParent;
    private boolean isLogin;
    private int userId;
    private List<CartDataTable> cartDataTableList = new ArrayList<>();

    private int pos;
    private int pQun;
    private int pId;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_home, container, false);

        initViews();
        initListeners();

        getSliderImages();

        // getCartItem();

        isLogin = sharedPreferences.getBoolean(Constants.USER_IS_LOGIN, false);

        if (Constants.topSellingProduct != null) {
            if (!Constants.topSellingProduct.isEmpty()) {
                recylerTimeDeal.setLayoutManager(new LinearLayoutManager(getActivity(), 
                LinearLayoutManager.HORIZONTAL, false));
                timeDealAdapter = new TopSellingAdapter(Constants.topSellingProduct, cartDataTableList, 
                getActivity());
                recylerTimeDeal.setAdapter(timeDealAdapter);

                clickListner(view);

            }
        } else {
            getTopSellingProducts(1);

        }

        if (Constants.latestProduct != null) {
            if (!Constants.latestProduct.isEmpty()) {
                homeDataModel.setLatestList(Constants.latestProduct);
                homeParentRecyclerAdapter = new DevicesParentRecyclerAdapter(getActivity(), 
                homeDataModel);
                recyclerView.setAdapter(homeParentRecyclerAdapter);

            }
        } else {
            getLatestProducts(1);

        }
        if (Constants.allProducts != null) {
            if (!Constants.allProducts.isEmpty()) {
                homeDataModel.setAllProductList(Constants.allProducts);
                homeParentRecyclerAdapter = new DevicesParentRecyclerAdapter(getActivity(), 
                homeDataModel);
                recyclerView.setAdapter(homeParentRecyclerAdapter);
            }
        } else {
            getAllProducts(1);

        }

        return view;
    }

    @Override
    public void onResume() {

        isLogin = sharedPreferences.getBoolean(Constants.USER_IS_LOGIN, false);

        //  if (isLogin) {
        userId = sharedPreferences.getInt(Constants.USER_ID, 0);

        cartViewModel.getCartDataTableLiveData(userId).observe(getActivity(), new 
          Observer<List<CartDataTable>>() {
            @Override
            public void onChanged(List<CartDataTable> cartDataTables) {
                if (cartDataTables != null) {
                    cartDataTableList = cartDataTables;

            }
        });

        //}

        super.onResume();
    }

    private void clickListner(View view1) {

        timeDealAdapter.setOnItemClickListener(new TopSellingAdapter.OnItemClickListener() {
            @Override
            public void onAddtoCartClick(View view, Product product) {

                Log.e("onAddtoCartClick", "called");

                userId = sharedPreferences.getInt(Constants.USER_ID, 0);
                progressDialog = new ProgressDialog(getActivity());
                progressDialog.setIndeterminate(true);
                progressDialog.setMessage("Please Wait...");
                progressDialog.setCancelable(false);
                progressDialog.setCanceledOnTouchOutside(false);
                progressDialog.show();
                viewParent = (View) view.getParent();

                progressDialog.dismiss();
                int quantity = 1;
                cartViewModel.addProductToCart(userId, product.getProduct_id(), 
                quantity).observe(getActivity(), new Observer<CartResponse>() {
                    @Override
                    public void onChanged(CartResponse cartResponse) {

                        if (cartResponse != null) {
                            progressDialog.dismiss();
                            if (cartResponse.getMessage().equals("Product added successfully")) {
                                progressDialog.dismiss();

                                CartDataTable cartDataTable = new CartDataTable();
                                cartDataTable.setProductId(product.getProduct_id());
                                cartDataTable.setProductQuantity(1);
                                cartDataTable.setUserId(userId);

                                cartViewModel.insertCart(cartDataTable);

                                progressDialog.invalidateOptionsMenu();

                            } else {
                                Toast.makeText(getActivity(), cartResponse.getMessage(), 
                                                  Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(getActivity(), "Something went wrong", 
                            Toast.LENGTH_SHORT).show();
                        }

                    }
                });

            }

            @Override
            public void updateCartData(int productId, int quantity, int position, View view) {

                pId = productId;
                pQun = quantity;
                pos = position;

                viewParent = (View) view.getParent();

                Log.d("updateCartData2", pId + "  " + pQun);

                CartDataTable cartDataTable = cartViewModel.getCart2(productId, userId);

                userId = sharedPreferences.getInt(Constants.USER_ID, 0);

                Log.d("userId2", String.valueOf(userId));

                if (cartDataTable != null) {

                    if (pQun == 0) {
                        cartViewModel.deleteCart(cartDataTable);

                    } else {
                        CartDataTable cartDataTable1 = new CartDataTable();
                        cartDataTable1.setProductQuantity(pQun);
                        cartDataTable1.setProductId(pId);
                        cartDataTable1.setCartId(cartDataTable.getCartId());
                        cartDataTable1.setUserId(userId);
                        cartViewModel.updateCart(cartDataTable1);

                        Log.d("cart2", "updated");

                    }
                }

            }
        });

    }

    private void getSliderImages() {

        if (AppClass.isOnline(getActivity())) {

            homeFragmentViewModel.getSliderImages().observe(getActivity(), new 
            Observer<SliderImagesResponse>() {

                @Override
                public void onChanged(SliderImagesResponse sliderImagesResponse) {

                    if (sliderImagesResponse.getStatus() == 1) {

                        SliderAdapterExample adapter = new SliderAdapterExample(getContext(), 
                        sliderImagesResponse.getData());

                        sliderView.setSliderAdapter(adapter);

                        sliderView.setSliderTransformAnimation(SliderAnimations.SIMPLETRANSFORMATION);
                        sliderView.setAutoCycleDirection(SliderView.AUTO_CYCLE_DIRECTION_BACK_AND_FORTH);
                        sliderView.setIndicatorSelectedColor(Color.WHITE);
                        sliderView.setIndicatorUnselectedColor(Color.GRAY);
                        sliderView.setScrollTimeInSec(4); //set scroll delay in seconds :
                        sliderView.startAutoCycle();

                    } else {
                        progressDialog.dismiss();
                        Toast.makeText(getContext(), ""+sliderImagesResponse.getMessage(), 
         Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } else {
            AppClass.offline(getActivity());
        }
    }

    private void getTopSellingProducts(int page) {

        if (AppClass.isOnline(getActivity())) {

            progressDialog.show();

            homeFragmentViewModel.getTopSellingProducts(page).observe(getActivity(), new 
                Observer<TopSellingResponse>() {

                @Override
                public void onChanged(TopSellingResponse topSellingResponse) {

                    if (topSellingResponse.getStatus() == 1) {

                        progressDialog.dismiss();

                        topSellingComplete = true;

                        Constants.topSellingProduct = topSellingResponse.getData();

                        recylerTimeDeal.setLayoutManager(new LinearLayoutManager(getActivity(), 
                        LinearLayoutManager.HORIZONTAL, false));
                        timeDealAdapter = new TopSellingAdapter(topSellingResponse.getData(), 
                        cartDataTableList, getActivity());
                        recylerTimeDeal.setAdapter(timeDealAdapter);

                        clickListner(view);

                        if (latestComplete || allproductsComplete) {
                            homeParentRecyclerAdapter.notifyDataSetChanged();
                        } else {
                            homeParentRecyclerAdapter = new DevicesParentRecyclerAdapter(getActivity(), 
                         homeDataModel);
                            recyclerView.setAdapter(homeParentRecyclerAdapter);
                        }

                    } else {
                        progressDialog.dismiss();
                        Toast.makeText(getContext(), ""+topSellingResponse.getMessage(), 
                     Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } else {
            AppClass.offline(getActivity());
        }
    }

    private void getLatestProducts(int page) {

        if (AppClass.isOnline(getActivity())) {

            progressDialog.show();

            homeFragmentViewModel.getLatestProducts(page).observe(getActivity(), new 
               Observer<TopSellingResponse>() {

                @Override
                public void onChanged(TopSellingResponse topSellingResponse) {

                    if (topSellingResponse.getStatus() == 1) {

                        progressDialog.dismiss();

                        latestComplete = true;

                        Constants.latestProduct = topSellingResponse.getData();
                        homeDataModel.setLatestList(topSellingResponse.getData());

                        if(topSellingComplete || allproductsComplete) {
                            homeParentRecyclerAdapter.notifyDataSetChanged();
                        } else {
                            homeParentRecyclerAdapter = new DevicesParentRecyclerAdapter(getActivity(), 
                            homeDataModel);
                            recyclerView.setAdapter(homeParentRecyclerAdapter);
                        }

                    } else {
                        progressDialog.dismiss();
                        Toast.makeText(getContext(), ""+topSellingResponse.getMessage(), 
                        Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } else {
            AppClass.offline(getActivity());
        }
    }

    private void getAllProducts(int page) {

        if (AppClass.isOnline(getActivity())) {

            progressDialog.show();

            homeFragmentViewModel.getAllProducts(page).observe(getActivity(), new 
                   Observer<TopSellingResponse>() {

                @Override
                public void onChanged(TopSellingResponse topSellingResponse) {

                    if (topSellingResponse.getStatus() == 1) {

                        progressDialog.dismiss();

                        allproductsComplete = true;
                        Constants.allProducts = topSellingResponse.getData();
                        homeDataModel.setAllProductList(topSellingResponse.getData());

                        if(topSellingComplete || latestComplete) {
                            homeParentRecyclerAdapter.notifyDataSetChanged();
                        } else {
                            homeParentRecyclerAdapter = new DevicesParentRecyclerAdapter(getActivity(), 
                            homeDataModel);
                            recyclerView.setAdapter(homeParentRecyclerAdapter);
                        }

                    } else {
                        progressDialog.dismiss();
                        Toast.makeText(getContext(), ""+topSellingResponse.getMessage(), 
                        Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } else {
            AppClass.offline(getActivity());
        }
    }

    private void getPoints(int userId) {
        pointsViewModel.getUserPointsById(userId).observe(getActivity(), new Observer<Points>() {
            @Override
            public void onChanged(Points points) {
                progressDialog.dismiss();
                if (points.getStatus() == 1) {
                    progressDialog.dismiss();
                    if (points.getTotalPoints() != null && points.getTotalDiscount() != null) {
                        totalPointsTextView.setText(points.getTotalPoints() + "");
                        totalPrice.setText(points.getTotalDiscount() + "");
                    } else {
                        Toast.makeText(getActivity(), "No Data Found", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    progressDialog.dismiss();
                    Toast.makeText(getActivity(), points.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void initViews() {

        homeFragmentViewModel = new ViewModelProvider(this).get(HomeFragmentViewModel.class);
        cartViewModel = new ViewModelProvider(this).get(CartViewModel.class);

        sliderView = view.findViewById(R.id.imageSlider);
        imageSliderDeals = view.findViewById(R.id.imageSliderDeals);
        recyclerView = view.findViewById(R.id.recyclerView);
        recylerTimeDeal = view.findViewById(R.id.recy_timeDeal);
        totalPointsTextView = view.findViewById(R.id.pointsTextView);
        totalPrice = view.findViewById(R.id.totalPrice);
        pointsViewModel = new ViewModelProvider(this).get(PointsViewModel.class);
        sharedPreferences = getActivity().getSharedPreferences(Constants.LOGIN_PREFERENCE, 
        Context.MODE_PRIVATE);
        int userId = sharedPreferences.getInt(Constants.USER_ID, 0);

    listTitleRecycler.add(0, "Top Selling");
    listTitleRecycler.add(1, "Latest Products");
    listTitleRecycler.add(2, "All Products");
    homeDataModel.setTitleList(listTitleRecycler);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), 
        LinearLayoutManager.VERTICAL, false));
        recyclerView.setHasFixedSize(true);

     progressDialog = new ProgressDialog(getContext(), R.style.exitDialogTheme);
     progressDialog.setIndeterminate(true);
     progressDialog.setMessage("Please wait...");
     progressDialog.setCancelable(false);
     progressDialog.setCanceledOnTouchOutside(false);

        getPoints(userId);
    }

    private void initListeners() {

        addLoungeToList();
        DealsSliderAdapter adapter = new DealsSliderAdapter(getContext(), loungeList);
        imageSliderDeals.setSliderAdapter(adapter);
        imageSliderDeals.setSliderTransformAnimation(SliderAnimations.SIMPLETRANSFORMATION);
        imageSliderDeals.setAutoCycleDirection(SliderView.AUTO_CYCLE_DIRECTION_BACK_AND_FORTH);
        imageSliderDeals.setScrollTimeInSec(4); //set scroll delay in seconds :
        imageSliderDeals.startAutoCycle();

    }

    public void addLoungeToList() {

        int i = 0;

        for (String name : imgNamesLounge) {
            ImagesListDM imagesListDM = new ImagesListDM();
            imagesListDM.setImg(imgResLounge[i]);
            imagesListDM.setNameImg(name);
            loungeList.add(imagesListDM);
            i++;

        }
    }

}

上螺旋适配器

package colon.semi.com.dealMall.adapters;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

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

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;

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

import colon.semi.com.dealMall.R;
import colon.semi.com.dealMall.Utils.Constants;
import colon.semi.com.dealMall.dataModels.CartDataTable;
import colon.semi.com.dealMall.dataModels.Product;
import colon.semi.com.dealMall.uiActivities.ProductDetailActivity;

public class
TopSellingAdapter extends RecyclerView.Adapter<TopSellingAdapter.SingleItemRowHolder> {

    private static OnItemClickListener mlistener; //just a variable
    private ArrayList<Product> topSellingList;

    private Context context;
    private List<CartDataTable> cartDataTables;

    int[] quantity;int[] pid;
    int size;

    public TopSellingAdapter(ArrayList<Product> topSellingList, List<CartDataTable> cartDataTableList, Context context) {
        this.topSellingList = topSellingList;
        this.cartDataTables = cartDataTableList;
        this.context = context;
    }

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

        SingleItemRowHolder viewHolder = (SingleItemRowHolder) holder;
        Product product = topSellingList.get(position);

        RequestOptions options = new RequestOptions()
                .centerInside()
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .skipMemoryCache(true)
                .priority(Priority.HIGH);
        Glide
                .with(context)
                .load(topSellingList.get(position).getImage_name())
                .apply(options)
                .into(viewHolder.image);

        viewHolder.name.setText(topSellingList.get(position).getProduct_title());
        viewHolder.price.setText(topSellingList.get(position).getPrice());

        viewHolder.linear_label.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(context, ProductDetailActivity.class);
                intent.putExtra(Constants.PRODUCT_OBJECT, product);
                context.startActivity(intent);

            }
        });

        holder.addtocart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                         if(mlistener!=null && position != RecyclerView.NO_POSITION){
                             viewHolder.addtocart.setVisibility(View.GONE);
                             viewHolder.cartLayout.setVisibility(View.VISIBLE);
                             viewHolder.quanTv.setText("1");

                             mlistener.onAddtoCartClick(v, topSellingList.get(position));

                         }
            }
        });

        if (cartDataTables != null && cartDataTables.size() > 0) {
            for (int i = 0; i < cartDataTables.size(); i++) {
                if (cartDataTables.get(i).getProductId() == product.getProduct_id()) {

                    viewHolder.addtocart.setVisibility(View.GONE);
                    viewHolder.cartLayout.setVisibility(View.VISIBLE);
                    viewHolder.quanTv.setText(String.valueOf(cartDataTables.get(i).getProductQuantity()));
                }
            }

             size = cartDataTables.size();
            quantity = new int[size];
            pid = new int[size];
        }

//        if (cartDataTables != null && cartDataTables.size() > 0) {

//            int size = cartDataTables.size();
//            int[] quantity = new int[size];
//            int[] pid = new int[size];

            Log.d("CartDataSize", String.valueOf(size));

            for (int i = 0; i < size; i++) {
                quantity[i] = cartDataTables.get(i).getProductQuantity();
                pid[i] = cartDataTables.get(i).getProductId();

                Log.d("CartData1", quantity[i] + "  " + pid[i]);

            }

            holder.addProdButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    for (int i = 0; i < size; i++) {
                        quantity[i]++;
                        viewHolder.quanTv.setText(String.valueOf(quantity[i]));
                    }

                   // int id = pid[size - 1];
                    //int q1 = quantity[size - 1];

                   // Log.d("q1", String.valueOf(q1));

                    for (int i = 0; i < size; i++) {

                        if (cartDataTables.get(i).getProductId() == product.getProduct_id()) {
                            // q1 = q1 + 1;
                            //Log.d("q2", String.valueOf(q1));

                            //Toast.makeText(context, String.valueOf(q1), Toast.LENGTH_SHORT).show();

                            mlistener.updateCartData(pid[i], quantity[i], holder.getAdapterPosition(), v);
                        }
                        else {

                            mlistener.updateCartData(pid[i], quantity[i], holder.getAdapterPosition(), v);
                        }

                    }

                }
            });

            holder.minusProdButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    for (int i = 0; i < size; i++) {

                        if (quantity[i] < 1) {

                            holder.cartLayout.setVisibility(View.GONE);
                            holder.addtocart.setVisibility(View.VISIBLE);

                        } else {

                            quantity[i]--;

                            if (quantity[i] < 1) {
                                holder.cartLayout.setVisibility(View.GONE);
                                holder.addtocart.setVisibility(View.VISIBLE);
                            }

                            viewHolder.quanTv.setText(String.valueOf(quantity[i]));
                        }

                    }

                    Toast.makeText(context, "Already added", Toast.LENGTH_SHORT).show();

                    for (int i = 0; i < size; i++) {

                        if (cartDataTables.get(i).getProductId() == product.getProduct_id()) {

                            mlistener.updateCartData(pid[i], quantity[i], holder.getAdapterPosition(), 
      v);
                        }
                        else {

                            mlistener.updateCartData(pid[i], quantity[i], holder.getAdapterPosition(), v);
                        }

                    }

                }
            });

    }

    @NonNull
    @Override
    public SingleItemRowHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.temp_top_selling_products, viewGroup, false);
        SingleItemRowHolder categoriesListVH = new SingleItemRowHolder(view);
        return categoriesListVH;
    }

    @Override
    public int getItemCount() {
        return (null != topSellingList ? topSellingList.size() : 0);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mlistener = listener;
    }

    public interface OnItemClickListener {
        void onAddtoCartClick(View view, Product product);
        void updateCartData(int productId, int quantity, int position, View view);
    }

    public class SingleItemRowHolder extends RecyclerView.ViewHolder {

        ImageView image;
        TextView name;
        TextView price;
        LinearLayout linear_label;

        Button addtocart;
        Button addProdButton;
        Button minusProdButton;
        TextView quanTv;
        RelativeLayout cartLayout;

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

            image = view.findViewById(R.id.image);
            name = view.findViewById(R.id.name);
            price = view.findViewById(R.id.price);
            linear_label = view.findViewById(R.id.linear_label);

            addtocart = view.findViewById(R.id.addToCartButtonHome);
            cartLayout = view.findViewById(R.id.rel_prodCart_home);
            addProdButton = view.findViewById(R.id.prodAddButtonHome);
            quanTv = view.findViewById(R.id.productQuanTextViewHome);
            minusProdButton = view.findViewById(R.id.prodMinusButtonHome);

        }

    }

}
eagi6jfj

eagi6jfj1#

第一次调用适配器构造函数时,cartdatatables列表中没有数据,并且由于我的条件if(cartdatatables!=null&&cartdatatables.size()>0),当我单击“添加到购物车”按钮时,他们在cartdatatables列表中找不到任何数据,因为我没有再次调用notifydatasetchanged()方法或调用适配器构造函数,并且我的addtocart click侦听器处于此条件下,如果(cartdatatables!=null&&cartdatatables.size()>0)这就是为什么“添加到购物车”按钮click listner不起作用的原因。
解决方案:调用notifydatasetchanged()方法或再次调用适配器构造函数。

相关问题