anber anber - 28 days ago 7
Android Question

Custom ListView adapter. TextChangedListener calls for wrong EditText

I have the list of travelers with custom adapter what consist two EditText - edtFirstName and edtLastName. I want when user enters text save changes to List, and when next button click send this List to another activity.

My code:

public class TravellersAdapter extends BaseAdapter {

private List<Traveler> itemsList;
private LayoutInflater inflater;
private Activity context;

public TravellersAdapter(Activity context, List<Traveler> itemsList) {
super();
this.itemsList = itemsList;
this.context = context;
inflater = LayoutInflater.from(context);
}

public int getCount() { return itemsList.size(); }

public Object getItem(int i) { return itemsList.get(i); }

public View getView(final int position, View view, ViewGroup viewGroup) {
if (view == null) {
view = inflater.inflate(R.layout.traveller_item, null);
}
Traveler currentItem = (Traveler) getItem(position);

EditText firstNameView = (EditText) view.findViewById(R.id.edtFirstName);
firstNameView.addTextChangedListener(new TextWatcher() {

public void afterTextChanged(Editable editable) {
currentItem.setFirstName(editable.toString());
}

});

return view;
}
}


For exemple List itemsList consist 5 items. When I edit 2-4 element all ok, but when I edit first or last element edited value assigned to all element in List. In dubugger i saw that method
afterTextChanged
calls 5 times with different values of
position
.
How to fix it?

Answer

in getView method, the parameter position gives the position of the newly created childView, not the clicked childView's position.

use this to get the correct position:

final int actual_position = myList.getPositionForView((View) v.getParent());

in onClick(View v); of the onClickListener of any View. In you case, you must implement onTextChangedListener for that EditText.

here:

myList is the ListView

v is the View you clicked, in this case the childView of the parent(myList).

Comments