How to get the Edit text position from Recycler Vi

2020-03-05 02:52发布

I want to know how to get position of Edit Text from Recycler View adapter.I used Card View with in that horizontal Linear Layout has three view TextView,EditText view and TextView. I want to get particular EditText Position from Textwatcher in Recycler View Adapter.

Adapter:

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);
                // 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);
                // 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));
        if (cartlistadp.get(position).getQty() != 0) {
            viewHolder.qty.setText(String.valueOf(cartlistadp.get(position).getQty()));
        } else {
            viewHolder.qty.setText("0");
        }
        YelloPage.imageLoader.displayImage(cartlistadp.get(position).getProductimg(), viewHolder.cartitemimg, options);
        viewHolder.qty.setTag(R.id.quantity, position);



    }

    @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 ViewHolder(final View view) {
            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);

            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);

            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, getAdapterPosition());
            //  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);

        }
        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 MyTextWatcher(View view, EditText editText, int adapterPosition) {
                this.view = view;
                this.editText = editText;
                // 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);
                int position = (int) qtyView.getTag(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();



                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("");
                    }

                    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 + ")");
            }
        }




    }




}

Thanks in Advance.

2条回答
老娘就宠你
2楼-- · 2020-03-05 03:06

Assume you use the following CustomViewHolder

public static class CustomViewHolder extends RecyclerView.ViewHolder {
    private TextView textView; 
    private TextView textView2;
    private EditText editText;
    private int position;
    public CustomViewHolder (View view) {
        super(view);
        textView = (TextView) view.findViewById(R.id.text_view);
        textView2 = (TextView) view.findViewById(R.id.text_view2);
        editText = (EditText) view.findViewById(R.id.edit_text);
        editText.addTextChangedListener(new CustomWatcher(this));
    }
}

and use the following CustomWatcher

public static class CustomWatcher implements TextWatcher {
    private int CustomViewHolder holder;
    public CustomWatcher(CustomViewHolder holder){
        this.holder = holder;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    public int getPosition(){
        return holder.position;
    }
}

Then, in your onBindViewHolder

@Override
public void onBindViewHolder(final CustomViewHolder holder, final int position) {
    holder.position = position;
}
查看更多
ゆ 、 Hurt°
3楼-- · 2020-03-05 03:16

In onBindViewHolder method of your Adapter, set tag for your EditText like this:

holder.editText.setTag(position);

And in your ViewHolder, add TextWatcher to your EditText

public static class ViewHolder extends RecyclerView.ViewHolder {

    EditText editText ;

    public ViewHolder(View itemView) {
        super(itemView);
        editText = itemView.findViewById(R.id.editText);
        MyTextWatcher textWatcher = new MyTextWatcher(editText);
        editText.addTextChangedListener(textWatcher);
    }
}

And here is your TextWatcher:

public class MyTextWatcher implements TextWatcher {
    private EditText editText;

    public MyTextWatcher(EditText editText) {
        this.editText = editText;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        int position = (int) editText.getTag();
        // Do whatever you want with position
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}

NOTE: Make sure you call setTag method from your EditText before calling setText method, else it will throw NullPointerException. Or alternatively you can add null check when calling getTag method.

UPDATE 1

If your EditText already has another tag set, use ID to identify tags. e.g. when setting tag use this:

holder.editText.setTag(R.id.editText, position);

where R.id.editText is valid id of any of your resources (See documentation for details).

And also when getting value:

int position = (int) editText.getTag(R.id.editText);
查看更多
登录 后发表回答