Android afterTextChanged得到EditText标记

问题描述:

我有一个DialogFragment包含一个ListView,与自定义适配器挂接到ListView。该列表显示了一组包含每个记录的EditText的项目,以允许用户输入数量。Android afterTextChanged得到EditText标记

当这些数量有变化时,我需要在适配器中更新我的数组,这意味着将EditText链接到数组中的特定元素。我使用EditText的getTag/setTag方法执行此操作。数组中的项是唯一的由两个属性:

LocationIDRefCode

这些都存储在我的TagData对象并设置在getView的点()。一旦价值发生变化,我试图使用EditText.getTag(),可悲的是无济于事。

问题是我不能访问afterTextChanged方法中的EditText

这里是我的适配器的getView()方法:

@Override 
public View getView(int i, View view, ViewGroup viewGroup) { 

    ItemModel item = (ItemModel) getItem(i); 

    TagData tagData = new TagData(); 
    tagData.setLocationID(item.getLocationID()); 
    tagData.setRefCode(item.getRefCode()); 

    EditText txtQuantity = ((EditText) view.findViewById(R.id.txtQuantity)); 
    txtQuantity.setTag(tagData); 
    txtQuantity.setText(String.valueOf(item.getQtySelected())); 

    txtQuantity.addTextChangedListener(this); 
    ... 
    return view; 
} 

在上面,我创建一个TagData对象,并使用setTag()它绑在EditText。我还在getView()上连接了addTextChangedListener。对于该afterTextChanged方法是这样的:

@Override 
public void afterTextChanged(Editable editable) { 
    EditText editText = (EditText)context.getCurrentFocus(); // This returns the WRONG EditText!? 

    // I need this 
    TagData locAndRefcode = (TagData) editText.getTag(); 
} 

this后,Activity.getCurrentFocus()应该回到问题的EditText,事实并非如此。相反,它会从DialogFragment背后的View中返回一个EditText

让我卡住了。如何从我的afterTextChanged方法中访问EditText的标记?

如果要将txtQuantity声明为final,然后将匿名新TextWatcher(){...}传递给addTextChangedListener,那么可以在afterTextChanged(可编辑)方法内直接使用txtQuantity。 希望这有助于。

+0

作为新到Java这种模式甚至没有想到我!完美解决了我的问题。谢谢+1 – Leigh 2014-11-23 21:37:58

您可以使用此代码

private Activity activity; 
private TextWatcher textWatcher = new TextWatcher() { 

     @Override 
     public void afterTextChanged(Editable s) { 
      View focView=activity.getCurrentFocus(); 
      /* if t use EditText.settxt to change text and the user has no 
      * CurrentFocus the focView will be null 
      */ 
      if(focView!=null) 
      { 
     EditText edit= (EditText) focView.findViewById(R.id.item_edit); 
     if(edit!=null&&edit.getText().toString().equals(s.toString())){  
     edit.getTag() 
     } 
     } 
     } 

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

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

     }  

    }; 
public EditAdapter(ArrayList<HashMap<String, String>> list, Activity activity){ 
    this.activity = activity; 
    this.list = list; 
    inflater = LayoutInflater.from(activity); 
} 
+0

我已经使用上面的@ dev.bmax解决方案解决了这个问题,但是它看起来也可以工作。感谢您的建议,我相信它可以帮助别人:) – Leigh 2014-12-31 14:09:10