2013-08-27 36 views
1

我創建了一個自定義ListView,它的每一行都包含一個TextView和一個EditText。一切都很完美,但我不知道我應該將TextChangeListener設置爲EditText,以便我可以設置/保存輸入的值。這裏是我的代碼:如何在自定義ListView中添加TextChangeListener?

RowItem.java

public class RowItem { 

    private String title; 
    private String value; 

    public RowItem(String title, String value) { 
     this.title = title; 
     this.value = value; 
    } 

    public String getValue() { 
     return value; 
    } 

    public void setValue(String value) { 
     this.value = value; 
    } 

    public String getTitle() { 
     return title; 
    } 

    public void setTitle(String title) { 
     this.title = title; 
    } 
} 

CustomList.java

public class CustomList extends ArrayAdapter<RowItem> { 

    Context context; 
    List<RowItem> items; 

    public CustomList(Context context, int resourceId, 
      List<RowItem> items) { 
     super(context, resourceId, items); 
     this.context = context; 
     this.items = items; 
    } 

    /*private view holder class*/ 
    private class ViewHolder { 
     TextView txtTitle; 
     EditText txtValue; 
    } 

    public View getView(int position, View convertView, ViewGroup parent) { 
     ViewHolder holder = null; 
     RowItem rowItem = getItem(position); 

     LayoutInflater mInflater = (LayoutInflater) context 
       .getSystemService(Activity.LAYOUT_INFLATER_SERVICE); 
     if (convertView == null) { 
      convertView = mInflater.inflate(R.layout.row_item, null); 
      holder = new ViewHolder(); 
      holder.txtTitle = (TextView) convertView.findViewById(R.id.textView1); 
      holder.txtValue = (EditText) convertView.findViewById(R.id.editText1); 
      convertView.setTag(holder); 
     } else 
      holder = (ViewHolder) convertView.getTag(); 

     holder.txtTitle.setText(rowItem.getTitle()); 
     holder.txtValue.setText(rowItem.getValue()); 

     return convertView; 
    } 
} 

什麼建議嗎?

回答

2

修改您的viewHolder以包含它指向的行的行號。

private class ViewHolder { 
    TextView txtTitle; 
    EditText txtValue; 
    int rowNumber; 
} 

設置ROWNUMBER總是

holder.txtValue.setText(rowItem.getValue()); 
holder.rowNumber = position; 

添加自定義的適配器上EDITTEXT一個onFocusListener並獲得通過下面的代碼編輯ROWNUMBER。

void onFocusChanged(View v, boolean hasFocus) { 
    ViewHolder holder = (ViewHolder)v.getParentView().getTag(); 
    int rowNo = holder.rowNumber; 
    //do rest of the stuff like modifying the array list. 
} 

不過,我認爲應該有比這個更容易的解決方案。

+0

您能否詳細介紹一下'onFocusChanged'? –

+0

setOnFocusListener和View.OnFocusListener處理焦點的開始和結束,就像Javascript一樣。當編輯文本通過編輯完成後,onFocusChanged被調用。 – Rajiv

相關問題