我想创建n个EditText
个对象...所以我使用LayoutInflater
在循环中执行此操作,该循环一直运行到n ...将视图添加到布局中但是如果我想为每个addTextChangedListener()
对象添加一个EditText
,只将侦听器添加到最后一个对象......这是一个关闭问题,我该如何解决?
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);
}
退回功能
public void ret(View v,TextView t){
EditText e=(EditText) v.findViewById(R.id.e1);
t.setText(e.getText());
}
主要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>
监听器只监听最后EditText
个视图中的更改...如何使其听取所有三个EditText
视图?
答案 0 :(得分:1)
这是因为您的v
和t
变量会在每个循环中被覆盖,使它们指向最后一个View和TextView。
尝试将代码更改为:
final View v=li.inflate(R.layout.addit, null);
final TextView t=(TextView) v.findViewById(R.id.a1);
答案 1 :(得分:0)
请执行以下操作。
edit_ll = (LinearLayout) findViewById(R.id.EditLinearLayout);
addEditText();
private void addEditText() {
LayoutInflater li = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
for(int i = 0; i < 3; i++) {
View v = li.inflate(R.layout.addit, null);
EditText e = (EditText) v.findViewById(R.id.e1);
e.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
// TODO Auto-generated method stub
System.out.println("--change--");
}
});
edit_ll.addView(v);
}
}
它获取所有ediText onTextChangeListener。试试吧。