Android afterTextChanged get EditText tag



>我有一个包含ListViewDialogFragment,带有连接到ListView的自定义适配器。该列表显示一堆项目,每条记录都有一个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();
}

根据这篇文章,Activity.getCurrentFocus()应该返回有问题的EditText,但它没有。相反,它从 DialogFragment 后面的视图中返回一个EditText

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

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

您可以使用此代码

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);
}
您可以使用

EditText#getEditableText方法:

@Override
public void afterTextChanged(Editable s) {
    if(editText.getEditableText() == s){
        //
        // Your code
        //
    }
}

最新更新