I want to create n number of EditText objects …so I am using LayoutInflater to do that in a loop which runs till n …The views are added to the layout but if I want to add a addTextChangedListener() to each of the EditText objects , the listener is added to only the last object …its a problem of closure ,how can I solve this ?
LinearLayout ll=(LinearLayout) findViewById(R.id.i1);
LayoutInflater li=(LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
for(int i=0;i<3;i++){
v=li.inflate(R.layout.addit, null); //v is a View declared as private member of the class
t=(TextView) v.findViewById(R.id.a1);//t is TextView declared as private member
EditText e=(EditText) v.findViewById(R.id.e1);
e.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
public void afterTextChanged(Editable arg0) {
ret(v, t);
}
});
ll.addView(v);
}
ret function
public void ret(View v,TextView t){
EditText e=(EditText) v.findViewById(R.id.e1);
t.setText(e.getText());
}
main xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/i1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
addit.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/l2"
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="vertical" >
<TextView
android:id="@+id/a1"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:text="" />
<EditText
android:id="@+id/e1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
</LinearLayout>
The listener only listens for changes in the last of the EditText views …how to make it to listen to all three EditText views?
This is because your
vandtvariables is overwritten in each loop, making them point to the last View and TextView.Try changing your code to: