在Recycler View中不按顺序显示的项目

时间:2016-06-21 05:27:52

标签: android android-layout android-recyclerview recycler-adapter

在我的Recycler View中,不按顺序显示项目,在运行程序时每次都会定期更改项目。 如何在Recycler View中按顺序显示项目。

代码:

 final CustomLinearLayoutManagercartpage layoutManager = new CustomLinearLayoutManagercartpage(CartItems.this, LinearLayoutManager.VERTICAL, false);
 recyleitems.setHasFixedSize(false);
 recyleitems.setLayoutManager(layoutManager);
 cartadapter = new CartlistAdapter(cart, CartItems.this);
 Log.i(String.valueOf(cartadapter), "cartadapter");
 recyleitems.setAdapter(cartadapter);
 recyleitems.setNestedScrollingEnabled(false);
 myView.setVisibility(View.GONE);
 cartadapter.notifyDataSetChanged();

适配器:

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

    private ArrayList < CartItemoriginal > cartlistadp;
    private ArrayList < Cartitemoringinaltwo > cartlistadp2;
    DisplayImageOptions options;
    private Context context;
    public static final String MyPREFERENCES = "MyPrefs";
    public static final String MYCARTPREFERENCE = "CartPrefs";
    public static final String MyCartQtyPreference = "Cartatyid";
    SharedPreferences.Editor editor;
    SharedPreferences shared,
    wishshared;
    SharedPreferences.Editor editors;
    String pos,
    qtyDelete;
    String date;
    String currentDateandTime;
    private static final int VIEW_TYPE_ONE = 1;
    private static final int VIEW_TYPE_TWO = 2;
    private static final int TYPE_HEADER = 0;
    private Double orderTotal = 0.00;
    DecimalFormat df = new DecimalFormat("0");
    Double extPrice;
    View layout,
    layouts;
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor QutId;

    boolean flag = false;


    public CartlistAdapter() {

    }
    public CartlistAdapter(ArrayList < CartItemoriginal > cartlistadp, Context context) {

        this.cartlistadp = cartlistadp;
        this.cartlistadp2 = cartlistadp2;
        this.context = context;
        options = new DisplayImageOptions.Builder().cacheOnDisk(true).cacheInMemory(true).showImageOnLoading(R.drawable.b2)
            .showImageForEmptyUri(R.drawable.b2).build();
        if (YelloPage.imageLoader.isInited()) {
            YelloPage.imageLoader.destroy();
        }
        YelloPage.imageLoader.init(ImageLoaderConfiguration.createDefault(context));
    }


    public int getItemViewType(int position) {

        if (cartlistadp.size() == 0) {
            Toast.makeText(context, String.valueOf(cartlistadp), Toast.LENGTH_LONG).show();
            return VIEW_TYPE_TWO;
        }
        return VIEW_TYPE_ONE;


    }


    @Override
    public CartlistAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {

        ViewHolder viewHolder = null;
        switch (position) {
            case VIEW_TYPE_TWO:
                View view2 = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.activity_cart, viewGroup, false);
                viewHolder = new ViewHolder(view2, new MyTextWatcher(viewGroup, position));
                // return view holder for your placeholder
                break;
            case VIEW_TYPE_ONE:
                View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cartitemrow, viewGroup, false);
                viewHolder = new ViewHolder(view, new MyTextWatcher(view, position));
                // return view holder for your normal list item
                break;
        }
        return viewHolder;

    }

    @Override
    public void onBindViewHolder(CartlistAdapter.ViewHolder viewHolder, int position) {
        viewHolder.productnames.setText(cartlistadp.get(position).getProductname());
        viewHolder.cartalisname.setText(cartlistadp.get(position).getAliasname());
        viewHolder.cartprice.setText("Rs" + " " + cartlistadp.get(position).getPrice());
        viewHolder.cartdelivery.setText(cartlistadp.get(position).getDelivery());
        viewHolder.cartshippin.setText(cartlistadp.get(position).getShippincharge());
        viewHolder.cartsellername.setText(cartlistadp.get(position).getSellername());
        viewHolder.Error.setText(cartlistadp.get(position).getError());
        viewHolder.qty.setTag(cartlistadp.get(position));
        viewHolder.myTextWatcher.updatePosition(position);
        if (cartlistadp.get(position).getQty() != 0) {
            viewHolder.qty.setText(String.valueOf(cartlistadp.get(position).getQty()));
            viewHolder.itemView.setTag(viewHolder);

        } else {
            viewHolder.qty.setText("0");
        }
        YelloPage.imageLoader.displayImage(cartlistadp.get(position).getProductimg(), viewHolder.cartitemimg, options);
    }

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

    public long getItemId(int position) {
        return position;
    }
    public Object getItem(int position) {
        return cartlistadp.get(position);
    }


    public class ViewHolder extends RecyclerView.ViewHolder {
        private TextView productnames, cartalisname, cartprice, cartdelivery, cartshippin, cartsellername, Error, total;
        private ImageView cartitemimg;
        private ImageButton wishbtn, removebtn;
        private LinearLayout removecart, movewishlist;
        private CardView cd;
        private EditText qty;
        private ImageView WishImg;
        public MyTextWatcher myTextWatcher;

        public ViewHolder(final View view, MyTextWatcher myTextWatcher) {
            super(view);
            productnames = (TextView) view.findViewById(R.id.cartitemname);
            cartalisname = (TextView) view.findViewById(R.id.cartalias);
            cartprice = (TextView) view.findViewById(R.id.CartAmt);
            cartdelivery = (TextView) view.findViewById(R.id.cartdel);
            cartshippin = (TextView) view.findViewById(R.id.shippingcrg);
            cartsellername = (TextView) view.findViewById(R.id.cartSellerName);
            cartitemimg = (ImageView) view.findViewById(R.id.cartimg);
            Error = (TextView) view.findViewById(R.id.error);
            this.myTextWatcher = myTextWatcher;

            removecart = (LinearLayout) view.findViewById(R.id.removecart);
            movewishlist = (LinearLayout) view.findViewById(R.id.movewishlist);

            WishImg = (ImageView) view.findViewById(R.id.wishimg);



            qty = (EditText) view.findViewById(R.id.quantity);
            qty.addTextChangedListener(myTextWatcher);

            String pid, qid;

            sharedPreferences = view.getContext().getSharedPreferences(MYCARTPREFERENCE, Context.MODE_PRIVATE);
            QutId = sharedPreferences.edit();
            Log.d("Position checking1 ---", String.valueOf(getAdapterPosition()));
            //MyTextWatcher textWatcher = new MyTextWatcher(view,qty);
            //  qty.addTextChangedListener(new MyTextWatcher(view,getAdapterPosition()));
            //qty.addTextChangedListener(textWatcher);


            qty.setOnKeyListener(new View.OnKeyListener() {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    qty.setSelection(qty.getText().length());
                    return false;
                }
            });

            wishshared = view.getContext().getSharedPreferences(MyPREFERENCES, context.MODE_PRIVATE);
            editors = view.getContext().getSharedPreferences(MyPREFERENCES, context.MODE_PRIVATE).edit();


            shared = view.getContext().getSharedPreferences(MYCARTPREFERENCE, context.MODE_PRIVATE);
            editor = view.getContext().getSharedPreferences(MYCARTPREFERENCE, context.MODE_PRIVATE).edit();


            cd = (CardView) view.findViewById(R.id.cv);
            productnames.setSingleLine(false);
            productnames.setEllipsize(TextUtils.TruncateAt.END);
            productnames.setMaxLines(2);

            //totalPrice();

            view.setClickable(true);
            //  view.setFocusableInTouchMode(true);

            removecart.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (cartlistadp.size() == 1) {
                        Intent list = new Intent(v.getContext(), Cart.class);
                        context.startActivity(list);
                        ((Activity) context).finish();
                        removeAt(getAdapterPosition());
                        Log.i(String.valueOf(getPosition()), "item");
                        Toast.makeText(context, "All items deleted from your WishList", Toast.LENGTH_LONG).show();
                    } else {
                        removeAt(getAdapterPosition());
                    }
                }
            });
            MovewishList();
            totalPrice();
        }


        private void totalPrice() {
            int price = 0;
            for (int j = 0; j < cartlistadp.size(); j++) {
                price += Integer.parseInt(cartlistadp.get(j).getPrice()) * (cartlistadp.get(j).getQty());
                String totalprice = String.valueOf(price);
                String count = String.valueOf(cartlistadp.size());
                CartItems.Totalamt.setText(totalprice);
                CartItems.cartcount.setText("(" + count + ")");
                CartItems.carttotalcount.setText("(" + count + ")");
            }
        }


        public void removeAt(int positions) {
            JSONArray test = new JSONArray();
            JSONArray test1 = new JSONArray();
            JSONArray test2 = new JSONArray();

            JSONArray item = null;
            JSONArray itemsQty = null;
            test1.put("0");
            test2.put("0");
            test.put(test1);
            test.put(test2);
            String channel = shared.getString(Constants.cartid, String.valueOf(test));
            pos = cartlistadp.get(getAdapterPosition()).getProductid();
            qtyDelete = String.valueOf(cartlistadp.get(getAdapterPosition()).getQty());

            try {
                JSONArray delteitems = new JSONArray(channel);

                itemsQty = delteitems.getJSONArray(0);
                item = delteitems.getJSONArray(1);

                for (int x = 0; x < itemsQty.length(); x++) {

                    if (pos.equalsIgnoreCase(itemsQty.getString(x))) {
                        itemsQty.remove(x);
                        cartlistadp.remove(positions);
                        notifyItemRemoved(positions);
                        notifyItemRangeChanged(positions, cartlistadp.size());
                        notifyDataSetChanged();
                    }
                }
                for (int y = 0; y < item.length(); y++) {
                    if (qtyDelete.equalsIgnoreCase(item.getString(y)))
                        item.remove(y);
                }
                String s = String.valueOf(delteitems);
                editor.putString(Constants.cartid, String.valueOf(delteitems));
                editor.apply();
            } catch (JSONException e) {
                e.printStackTrace();
            }


        }


        public void MovewishList() {



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

                    if (cartlistadp.size() == 1) {
                        pos = cartlistadp.get(getAdapterPosition()).getProductid();
                        JSONArray items3;
                        if (!flag) {
                            //    wishlist.setBackgroundResource(R.drawable.wishnew);
                            flag = true;
                            String channel = wishshared.getString(Constants.productid, "['']");
                            JSONArray items;
                            String wishitem;
                            if (TextUtils.isEmpty(channel)) {
                                items = new JSONArray();
                                items.put(String.valueOf(pos));
                                wishitem = String.valueOf(items);
                                editors.putString(Constants.productid, wishitem);
                                editors.apply();
                                removeAt(getAdapterPosition());
                                Toast.makeText(context, "cartItems", Toast.LENGTH_LONG).show();
                                flag = false;

                            } else {

                                try {

                                    Boolean found = false;
                                    items = new JSONArray(channel);
                                    for (int x = 0; x < items.length(); x++) {
                                        if (pos.equalsIgnoreCase(items.getString(x))) {
                                            found = true;
                                            removeAt(getAdapterPosition());
                                            Toast.makeText(context, "cartItems1", Toast.LENGTH_LONG).show();
                                        }
                                    }
                                    if (!found) {
                                        items.put(String.valueOf(pos));
                                        wishitem = String.valueOf(items);
                                        editors.putString(Constants.productid, wishitem);
                                        removeAt(getAdapterPosition());
                                        Toast.makeText(context, Constants.productid, Toast.LENGTH_LONG).show();
                                        Log.i(Constants.productid, "wishitems");

                                    }
                                    editors.apply();
                                    flag = false;

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }

                            Intent list = new Intent(view.getContext(), Cart.class);
                            context.startActivity(list);
                            ((Activity) context).finish();
                        } else {
                            removeAt(getAdapterPosition());
                            Intent list = new Intent(view.getContext(), Cart.class);
                            context.startActivity(list);
                            ((Activity) context).finish();
                        }


                    } else {

                        pos = cartlistadp.get(getAdapterPosition()).getProductid();
                        if (!flag) {
                            //    wishlist.setBackgroundResource(R.drawable.wishnew);
                            flag = true;

                            String channel = wishshared.getString(Constants.productid, "['']");
                            JSONArray items;
                            String wishitem;
                            if (TextUtils.isEmpty(channel)) {
                                items = new JSONArray();
                                items.put(String.valueOf(pos));
                                wishitem = String.valueOf(items);
                                editors.putString(Constants.productid, wishitem);
                                editors.apply();
                                removeAt(getAdapterPosition());
                                Toast.makeText(context, "cartItems", Toast.LENGTH_LONG).show();
                                flag = false;

                            } else {

                                try {

                                    Boolean found = false;
                                    items = new JSONArray(channel);
                                    for (int x = 0; x < items.length(); x++) {
                                        if (pos.equalsIgnoreCase(items.getString(x))) {
                                            found = true;
                                            removeAt(getAdapterPosition());
                                        }
                                    }
                                    if (!found) {
                                        items.put(String.valueOf(pos));
                                        wishitem = String.valueOf(items);
                                        editors.putString(Constants.productid, wishitem);
                                        removeAt(getAdapterPosition());
                                        Log.i(Constants.productid, "wishitems");
                                    }
                                    editors.apply();
                                    flag = false;

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        } else {
                            removeAt(getAdapterPosition());
                        }

                    }

                }



            });

        }




    }

    public class InputFilterMinMax implements InputFilter {

        private int min, max;

        public InputFilterMinMax(int min, int max) {
            this.min = min;
            this.max = max;
        }

        public InputFilterMinMax(String min, String max) {
            this.min = Integer.parseInt(min);
            this.max = Integer.parseInt(max);
        }

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            try {
                int input = Integer.parseInt(dest.toString() + source.toString());
                if (isInRange(min, max, input))
                    return null;
            } catch (NumberFormatException nfe) {}
            return "";
        }

        private boolean isInRange(int a, int b, int c) {
            return b > a ? c >= a && c <= b : c >= b && c <= a;
        }
    }


    private class MyTextWatcher implements TextWatcher {
        private View view;
        private EditText editText;
        private int position;

        //private int position;
        private MyTextWatcher(View view, int position) {
            this.view = view;
            this.position = position;
            // this.position = adapterPosition;


            //  cartlistadp.get(position).getQty() = Integer.parseInt((Caption.getText().toString()));
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            //do nothing
        }
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //   EditText qtyView = (EditText) view.findViewById(R.id.quantity);

            Log.i("editextpostion", String.valueOf(position));
        }

        public void afterTextChanged(Editable s) {

            DecimalFormat df = new DecimalFormat("0");
            String qtyString = s.toString();
            int quantity = qtyString.equals("") ? 0 : Integer.valueOf(qtyString);
            String quty = String.valueOf(quantity);

            EditText qtyView = (EditText) view.findViewById(R.id.quantity);
            CartItemoriginal product = (CartItemoriginal) qtyView.getTag();

            //   int position = (int) view.qtyView.getTag();

            Log.d("postion is qtytag", "Position is: " + product);
            qtyView.setFilters(new InputFilter[] {
                new InputFilterMinMax(product.getMinquantity(), product.getMaxquantity())
            });

            if (product.getQty() != quantity) {

                Double currPrice = product.getExt();
                Double price = Double.parseDouble(product.getPrice());
                int maxaty = Integer.parseInt(product.getMaxquantity());
                int minqty = Integer.parseInt(product.getMinquantity());

                if (quantity < maxaty) {
                    extPrice = quantity * price;
                } else {
                    Toast.makeText(context, "Sorry" + " " + " " + "we are shipping only" + " " + " " + maxaty + "  " + " " + "unit of quantity", Toast.LENGTH_LONG).show();
                }
                Double priceDiff = Double.valueOf(df.format(extPrice - currPrice));

                product.setQty(quantity);
                product.setExt(extPrice);

                TextView ext = (TextView) view.findViewById(R.id.CartAmt);

                if (product.getQty() != 0) {
                    ext.setText("Rs." + " " + df.format(product.getExt()));
                } else {
                    ext.setText("0");
                }


                if (product.getQty() != 0) {
                    qtyView.setText(String.valueOf(product.getQty()));
                } else {
                    qtyView.setText("");
                }


                JSONArray test = new JSONArray();
                JSONArray test1 = new JSONArray();
                JSONArray test2 = new JSONArray();
                JSONArray items = null;
                JSONArray itemsQty = null;
                test1.put("0");
                test2.put("0");
                test.put(test1);
                test.put(test2);
                JSONArray listitems = null;
                //String Sharedqty= String.valueOf(cartlistadp.get(getAdapterPosition()).getQty());


                String channel = (shared.getString(Constants.cartid, String.valueOf(test)));

                try {
                    listitems = new JSONArray(channel);
                    itemsQty = listitems.getJSONArray(1);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                try {
                    if (itemsQty != null) {
                        itemsQty.put(position + 1, qtyString);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                try {
                    if (listitems != null) {
                        listitems.put(1, itemsQty);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                QutId.putString(Constants.cartid, String.valueOf(listitems));
                QutId.apply();

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

                totalPrice();
            }

            return;
        }

        private void totalPrice() {
            int price = 0;
            for (int j = 0; j < cartlistadp.size(); j++) {
                price += Integer.parseInt(cartlistadp.get(j).getPrice()) * (cartlistadp.get(j).getQty());
                String totalprice = String.valueOf(price);
                String count = String.valueOf(cartlistadp.size());
                CartItems.Totalamt.setText(totalprice);
                CartItems.cartcount.setText("(" + count + ")");
                CartItems.carttotalcount.setText("(" + count + ")");
            }
        }

        public void updatePosition(int position) {
            this.position = position;
        }
    }




}

先谢谢。

1 个答案:

答案 0 :(得分:1)

对于排序,您需要使用Java的Collection.sort方法,并且还需要实现类似的界面来定义您的比较。

CartItemoriginal implements Comparable {
     public int compareTo(Object obj)  { }  }

更新

public class CartItemoriginal implements Comparable<CartItemoriginal > {

    private Float val;
    private String id;

    public CartItemoriginal (Float val, String id){
        this.val = val;
        this.id = id;
    }

    @Override
    public int compareTo(ToSort f) {

        if (val.floatValue() > f.val.floatValue()) {
            return 1;
        }
        else if (val.floatValue() <  f.val.floatValue()) {
            return -1;
        }
        else {
            return 0;
        }

    }

    @Override
    public String toString(){
        return this.id;
    }
}

并使用

Collections.sort(sortList);