Android中获取EditText标签的afterTextChanged方法

3
我有一个包含ListView的DialogFragment,使用自定义适配器连接到ListView。该列表显示了许多条目,每条记录都有一个EditText用于输入数量。
当其中任何一个数量发生改变时,我需要更新适配器内的数组,这意味着将EditText与数组中的特定元素链接起来。我使用EditText的getTag / setTag方法来完成此操作。数组中的项目由两个属性唯一标识:LocationID和RefCode 这些存储在我的TagData对象中,并在getView()点设置。不幸的是,我尝试在值更改后使用EditText.getTag(),但无济于事。
问题在于我无法在afterTextChanged方法中访问EditText。
这是我的Adapter的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();
}

根据这个帖子,Activity.getCurrentFocus()应该返回相关的EditText,但实际上它返回的是DialogFragment后面的EditText
这让我陷入了困境。我该如何在afterTextChanged方法中访问EditText的标记?
3个回答

4
如果你将txtQuantity声明为final,然后将一个匿名的新TextWatcher() { ... }传递到addTextChangedListener中,那么你就可以直接在afterTextChanged(Editable s)方法中使用txtQuantity。 希望这能帮到你。

作为一个对Java新手来说,我甚至没有想到这种模式!完美地解决了我的问题。谢谢你!+1 - undefined

2

您可以使用此代码

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

我已经使用@dev.bmax上面的解决方案解决了这个问题,然而这个解决方案看起来也能够工作。感谢您的建议,我相信它可能会帮助其他人 :) - undefined

-1
你可以使用EditText#getEditableText方法:
@Override
public void afterTextChanged(Editable s) {

    if(editText.getEditableText() == s){
        //
        // Your code
        //
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接