如何使用android中的Text Watcher从Recycler View适配器获取Edit文本位置

时间:2016-06-20 06:16:09

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

我想知道如何从Recycler View适配器获取编辑文本的位置。我使用过 卡片视图中的水平线性布局有三个视图TextView,EditText视图和TextView。 我想从Recycler View Adapter中的Textwatcher获取特定的EditText位置。

适配器:

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




    }




}

先谢谢。

2 个答案:

答案 0 :(得分:5)

onBindViewHolder的{​​{1}}方法中,为Adapter设置标记,如下所示:

EditText

holder.editText.setTag(position); 中,将ViewHolder添加到TextWatcher

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

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) { } } 方法之前从setTag调用EditText方法,否则会抛出setText。或者,您也可以在调用NullPointerException方法时添加null检查。

更新1

如果您的getTag已设置了其他标记,请使用EditText标识标记。例如设置标签时使用:

ID

其中holder.editText.setTag(R.id.editText, position); 是您的任何资源的有效ID(有关详细信息,请参阅documentation)。

并且在获得价值时:

R.id.editText

答案 1 :(得分:1)

假设您使用以下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));
    }
}

并使用以下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;
    }
}

然后,在onBindViewHolder

@Override
public void onBindViewHolder(final CustomViewHolder holder, final int position) {
    holder.position = position;
}