2014-11-23 75 views
0

我有一個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的標記?

回答

3

如果要將txtQuantity聲明爲final,然後將匿名新TextWatcher(){...}傳遞給addTextChangedListener,那麼可以在afterTextChanged(可編輯)方法內直接使用txtQuantity。 希望這有助於。

+0

作爲新到Java這種模式甚至沒有想到我!完美解決了我的問題。謝謝+1 – Leigh 2014-11-23 21:37:58

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

我已經使用上面的@ dev.bmax解決方案解決了這個問題,但是它看起來也可以工作。感謝您的建議,我相信它可以幫助別人:) – Leigh 2014-12-31 14:09:10