android回收器视图两个列表显示在一起



https://i.stack.imgur.com/HZ3v6.png

这是回收站视图的图片

我不明白是什么原因造成了这个问题。所以,伙计们,请你们给出一个可能的原因。

提前感谢。

public class ProductAdaptor extends RecyclerView.Adapter<ProductAdaptor.ProductViewHolder> {
    //implements Filterable {
    private final LayoutInflater inflator;
    private final List<ProductInfo> products;
    private Context context;
    private ProductAdapterListener listener;
    ImageLoader imageLoader = VolleySingleton.getInstance().getImageLoader();
    //private List<ProductInfo> BackupProducts= Collections.emptyList();
    ProductInfo current;
    public ProductAdaptor(Context context, List<ProductInfo> data, ProductAdapterListener listener) {
        inflator = LayoutInflater.from(context);
        products = data;
        this.context = context;
        this.listener = listener;
        //BackupProducts=data;
    }
    @Override
    public ProductAdaptor.ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflator.inflate(R.layout.custom_product, parent, false);
        ProductViewHolder holder = new ProductViewHolder(view);
        return holder;
    }
    @Override
    public void onBindViewHolder(final ProductAdaptor.ProductViewHolder holder, final int position) {
        current = products.get(position);
        holder.title.setText(current.getName());
        holder.icon.setImageUrl(current.getImage(), imageLoader);
        holder.price.setText("Price: Rs. " + current.getPrice());
        holder.description.setText(current.getDescription());
        holder.add_Cart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                products.get(position).setQuantity(Integer.parseInt(holder.etQuantity.getText().toString()));
                listener.onAddToCartPressed(products.get(position));
            }
        });
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("Reading Position", "" + current.getId());
                Intent base = new Intent(context, Products.class);
                base.putExtra("product_id", Integer.parseInt(products.get(position).getId()));
                base.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
                context.startActivity(base);
            }
        });
    }
    public void setData(List<ProductInfo> list) {
        products.clear();
        products.addAll(list);
        notifyDataSetChanged();
    }
    /*
    public void flushFilter(){
        products.clear();
        products.addAll(BackupProducts);
        notifyDataSetChanged();
    }*/
    public void animateTo(List<ProductInfo> models) {
        applyAndAnimateRemovals(models);
        applyAndAnimateAdditions(models);
        applyAndAnimateMovedItems(models);
    }
    private void applyAndAnimateRemovals(List<ProductInfo> newModels) {
        for (int i = products.size() - 1; i >= 0; i--) {
            final ProductInfo model = products.get(i);
            if (!newModels.contains(model)) {
                removeItem(i);
            }
        }
    }
    private void applyAndAnimateAdditions(List<ProductInfo> newModels) {
        for (int i = 0, count = newModels.size(); i < count; i++) {
            final ProductInfo model = newModels.get(i);
            if (!products.contains(model)) {
                addItem(i, model);
            }
        }
    }
    private void applyAndAnimateMovedItems(List<ProductInfo> newModels) {
        for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) {
            final ProductInfo model = newModels.get(toPosition);
            final int fromPosition = products.indexOf(model);
            if (fromPosition >= 0 && fromPosition != toPosition) {
                moveItem(fromPosition, toPosition);
            }
        }
    }
    public ProductInfo removeItem(int position) {
        final ProductInfo model = products.remove(position);
        notifyItemRemoved(position);
        return model;
    }
    public void addItem(int position, ProductInfo model) {
        products.add(position, model);
        notifyItemInserted(position);
    }
    public void moveItem(int fromPosition, int toPosition) {
        final ProductInfo model = products.remove(fromPosition);
        products.add(toPosition, model);
        notifyItemMoved(fromPosition, toPosition);
    }

    @Override
    public int getItemCount() {
        return products.size();
    }
    /*
    @Override
    public Filter getFilter() {
        //flushFilter();
        return new CardFilter(this,BackupProducts);
    }
    */

    public interface ProductAdapterListener {
        void onAddToCartPressed(ProductInfo product);
    }

    static class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView title;
        NetworkImageView icon;
        TextView price;
        TextView description;
        LinearLayout add_Cart;
        TextView etQuantity;
        public ProductViewHolder(final View itemView) {
            super(itemView);
            icon = (NetworkImageView) itemView.findViewById(R.id.productImage);
            title = (TextView) itemView.findViewById(R.id.productName);
            price = (TextView) itemView.findViewById(R.id.productPrice);
            description = (TextView) itemView.findViewById(R.id.productDescription);
            add_Cart = (LinearLayout) itemView.findViewById(R.id.add_cart);
            etQuantity = (TextView) itemView.findViewById(R.id.quanity);
        }
        @Override
        public void onClick(View v) {
        }
    }
/*
    //FILTER THE SEARCH RESULTS
    private static class CardFilter extends Filter {
        private final ProductAdaptor adapter;
        private final List<ProductInfo> originalList;
        private final List<ProductInfo> filteredList;
        private CardFilter(ProductAdaptor adapter, List<ProductInfo> originalList) {
            super();
            this.adapter = adapter;
            this.originalList = new LinkedList<ProductInfo>(originalList);
            this.filteredList = new ArrayList<ProductInfo>();
        }
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            filteredList.clear();
            final FilterResults results = new FilterResults();
            if (constraint.length() == 0) {
                filteredList.addAll(originalList);
            } else {
                final String filterPattern = constraint.toString().toLowerCase().trim();
                for (final ProductInfo productInfo : originalList) {
                    if (productInfo.getName().toLowerCase().trim().contains(filterPattern)) {
                        filteredList.add(productInfo);
                    }
                }
            }
            results.values = filteredList;
            results.count = filteredList.size();
            return results;
        }
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            adapter.setData((ArrayList<ProductInfo>) results.values);
            adapter.notifyDataSetChanged();

        }
    }
    */
}

产品片段

public class ProductFragment extends Fragment  implements SearchView.OnQueryTextListener,ProductAdaptor.ProductAdapterListener {
    private static final String TAG = ProductFragment.class.getSimpleName();
    private ProductAdaptor adapter;
    private RecyclerView recyclerView;
    private RequestQueue requestQueue;
    private VolleySingleton volleySingleton;
    // To store all the products
    private List<ProductInfo> productsList=new ArrayList<>();
    ProductAdaptor.ProductAdapterListener listener;
     //Progress dialog
    private ProgressDialog pDialog;
    public static ProductFragment newInstance() {
        return new ProductFragment();
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pDialog = new ProgressDialog(getActivity());
        pDialog.setCancelable(false);
        listener=this;
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View layout=inflater.inflate(R.layout.product_fragment,container,false);
        recyclerView= (RecyclerView) layout.findViewById(R.id.productList);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        pDialog.setMessage("Fetching products...");
        showpDialog();
        volleySingleton=VolleySingleton.getInstance();
        requestQueue=volleySingleton.getRequestQueue();
        JsonObjectRequest jsObjRequest = new JsonObjectRequest
                (Request.Method.GET, AppConfig.URL_PRODUCTS, (String) null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        //hide the progress dialog
                        hidepDialog();
                        adapter=new ProductAdaptor(getActivity(),parseJSONOResponse(response),listener);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        Toast.makeText(MyApplication.getAppContext(),
                                error.getMessage(), Toast.LENGTH_SHORT).show();
                        // hide the progress dialog
                        hidepDialog();
                    }
                });
        // Wait 20 seconds and don't retry more than once

        requestQueue.add(jsObjRequest);
        recyclerView.setAdapter(adapter);
        return layout;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setHasOptionsMenu(true);

    }
    /*
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_main,menu);
        final MenuItem item = menu.findItem(R.id.search);
        final SearchView searchView = (android.support.v7.widget.SearchView) MenuItemCompat.getActionView(item);
        searchView.setOnQueryTextListener(this);
    }
*/
    public boolean PerformSearch(String searchString){
        //adapter.getFilter().filter(searchString);
        return true;
    }
    public void setDataSet(List<ProductInfo> newDataSet){
        adapter=new ProductAdaptor(MyApplication.getAppContext(),newDataSet,this);
        recyclerView.swapAdapter(adapter, false);
        //new way of filtering data
    }

    private List<ProductInfo> parseJSONOResponse(JSONObject response){
        try {
            JSONArray products = response.getJSONArray("products");
            for (int i = 0; i < products.length(); i++) {
                JSONObject product = (JSONObject) products
                        .get(i);
                String id = product.getString("product_id");
                String name = product.getString("name");
                String description = product
                        .getString("description");
                String image = AppConfig.URL_IMAGE_PRODUCTS + product.getString("image");
                BigDecimal price = new BigDecimal(product
                        .getString("price"));
                ProductInfo p = new ProductInfo(id, name, description,
                        image, price);
                productsList.add(p);
            }
            return productsList;
        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(getActivity(),
                    "Error: " + e.getMessage(),
                    Toast.LENGTH_LONG).show();
        }
        return productsList;
    }
    @Override
    public void onAddToCartPressed(ProductInfo product) {
        CartHandler cartHandler=new CartHandler(MyApplication.getAppContext());
        Log.d("Insert: ", "Inserting ..");
        if (cartHandler.getProductsInCartCount()==0) {
            cartHandler.addProductInCart(product);
            Toast.makeText(MyApplication.getAppContext(),
                    product.getName() + " added to cart!", Toast.LENGTH_SHORT).show();
        }
        else{
            ProductInfo temp=cartHandler.getProductInCart(Integer.parseInt(product.getId()));
            if (temp!=null){
                cartHandler.updateProduct(product);
                Toast.makeText(MyApplication.getAppContext(),
                        product.getName() + " added to cart!", Toast.LENGTH_SHORT).show();
            }else
            {
                cartHandler.addProductInCart(product);
                Toast.makeText(MyApplication.getAppContext(),
                        product.getName() + " added to cart!", Toast.LENGTH_SHORT).show();
            }
        }

    }

    private void showpDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }
    private void hidepDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }
    @Override
    public boolean onQueryTextChange(String query) {
        final List<ProductInfo> filteredModelList = filter(productsList, query);
        adapter.animateTo(filteredModelList);
        recyclerView.scrollToPosition(0);
        return true;
    }
    private List<ProductInfo> filter(List<ProductInfo> models, String query) {
        query = query.toLowerCase();
        final List<ProductInfo> filteredModelList = new ArrayList<>();
        for (ProductInfo model : models) {
            final String text = model.getName().toLowerCase();
            if (text.contains(query)) {
                filteredModelList.add(model);
            }
        }
        return filteredModelList;
    }
}

这个问题是由重叠的片段引起的,我像这个一样启动了片段

fragment=ProductFragment.newInstance();
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.productFragment,fragment )
                    .commit();

所以让它简单的

fragment=ProductFragment.newInstance();

解决了我的问题。

感谢大家的帮助@MohammadAllam

最新更新