实现TextWatcher

时间:2016-01-14 06:29:09

标签: android android-recyclerview textwatcher android-viewholder

我正在尝试在RecycleView的Viewholder中为编辑文本实现TextWatcher。编辑edittext时,我想得到适配器的位置,以获取recycleview中该行的其他信息。

我不确定是否要创建一个自定义textwatcher,它将viewholder作为参数(以便它可以调用getAdapterPosition),因为当数据发生更改时,我担心当recycleview回收内容时,edittext可能会使用不同的viewholder

 public static class DIViewHolder extends RecyclerView.ViewHolder {
        TextView invName;
        EditText invWasted;
        EditText invEnding;
        EditText invAdded;

        DIViewHolder(View itemView) {
            super(itemView);
            invName = (TextView)itemView.findViewById(R.id.di_inventory_name);
            invAdded = (EditText)itemView.findViewById(R.id.di_inventory_added);
            invWasted = (EditText)itemView.findViewById(R.id.di_inventory_wasted);
            invEnding = (EditText)itemView.findViewById(R.id.di_inventory_end);
        }
    }


   @Override
    public DIViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_item_daily_inventory, viewGroup, false);
        DIViewHolder pvh = new DIViewHolder(v);

        return pvh;
    }

1 个答案:

答案 0 :(得分:0)

Try this 

       public static class DIViewHolder extends RecyclerView.ViewHolder implements TextWatcher {
                TextView invName;
                EditText invWasted;
                EditText invEnding;
                EditText invAdded;

                DIViewHolder(View itemView) {
                    super(itemView);
                    invName = (TextView)itemView.findViewById(R.id.di_inventory_name);
                    invAdded = (EditText)itemView.findViewById(R.id.di_inventory_added);
                    invWasted = (EditText)itemView.findViewById(R.id.di_inventory_wasted);
                    invEnding = (EditText)itemView.findViewById(R.id.di_inventory_end);
                    invName.addTextChangedListener(this);
                }

         @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 = getAdapterPosition();
                    /* Use this position to retrieve the object for the row and make the 
    changes, preferably have an interface defined which would communicate back the 
position to activity / fragment; Do data object changes there. */ 
                     RowObject object = yourRowObjectsList.get(position);
                     //Do changes to your row object.
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            }
相关问题