1

我正在嘗試爲RecycleView的Viewholder內的編輯文本實現TextWatcher。當編輯edittext時,我想要獲取適配器的位置以獲取recycleview中該行的其他信息。實現TextWatcher的Android RecycleView適配器(EditText)

我不知道是否創建一個自定義的textwatcher,它將一個參數作爲參數(以便它可以調用getAdapterPosition),因爲當數據更改時,恐怕editcycle可能會在recycleview回收內容。

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

回答

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

       } 
      }