【发布时间】:2013-12-16 14:44:15
【问题描述】:
有一个应用程序,我可以在其中以编程方式创建线性布局。 LinearLayouts 略有不同,但它们都包含多个视图。其中一些有一个带有 TextWatcher 的 EditText 字段。创建这些视图时,我想使用 EditText 字段中首选项中的旧存储值。
当我在 TextWtacher 之前使用 .setText(old_value) 时,EditText 字段中的数据是正确的,但从不调用依赖于 TextWatcher 函数的计算。 当我尝试在 TextWtacher 之后使用 .setText(old_value) 时,我得到一个 NullPointerException。
下面是一个简短的代码示例...
(LinearLayout) linearLayout = new LinearLayout();
linearLayout.setId(ll_counter++);
while (have more rows to process) {
BUTTON-VIEW-code;
linearLayout.addView();
TEXT-VIEW-code
linearLayout.addView(TEXT-VIEW);
editText = new EditText(this);
editText.setId(et_counter++);
editText.setTag("SomeTag");
editText.setText(old_value); // Works, but no calculations
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// do calculations and update add_text-field.
}
public void beforeTextChanged(Editable s) {
// nothing here
}
public void onTextChanged(Editable s) {
// nothing here
}
});
editText.setText(old_value); // Doesn't Works, NULL PONTER EXCEPTION
linearLayout.addView(editText);
}
editText.setText 是否应该在 linearLayout.addView(editText); 之后?像这样? (当然还有一些修改......)
linearLayout.addView(editText);
editText.setText(old_value);
【问题讨论】:
-
不确定在 while 循环中创建
TextWatcher是否是最好的选择。请记住,除非您自己摆脱它,否则文本观察器将永远为您服务。您可能会遇到问题,因为当您真的只需要一个时,您会不断创建新的 TextWatcher。 -
editText.setId(et_counter++); && 线性布局.setId(ll_counter++);看起来也有点冒险,取决于 et_counter 和 ll_counter 的默认值。同样正如@pasta12 提到的,在循环中添加 TextWatcher 没有多大意义。根据您的逻辑,您似乎只需要一个 TextWatcher 来创建多个。
-
Pasta12,我会调查的。因为,正如你所说,我只需要一个 TextWtacher。还有@Gaurav Arora,我的 id 比在这个例子中创建的更可靠......但是感谢两者的回复
-
.setText(),在 addTextChangedListener() 工作之前 .setTest() 在 addTextChangedListener() 引发 NPE 之后。我看到的唯一原因是您的 TextWatcher 方法有问题。您能否发布您的 NPE 堆栈跟踪或 TextWatcher 的源代码。
-
@Gaurav Arora 为了从 editText.setTag() 和 editText.setID() 等访问数据,我在 afterTextChanged 中使用 >View v = getCurrentFocus();
标签: android android-layout android-edittext settext