【问题标题】:setText after TextWatcher on a programatically created EditText在以编程方式创建的 EditText 上的 TextWatcher 之后的 setText
【发布时间】: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


【解决方案1】:

在 while 循环之外创建 edittext

editText = new EditText(this);

 while (have more rows to process) {
    BUTTON-VIEW-code;
    linearLayout.addView();
    TEXT-VIEW-code
    linearLayout.addView(TEXT-VIEW);

【讨论】:

  • 不是一个选项,因为循环可能会创建几个需要 TextWatcher 的编辑文本字段。每个linearLayout都可以有一个editText...
  • 我当然可以将editText-ids存储在一个数组中,然后在while循环之后应用它们......
【解决方案2】:

已解决:完全重组代码并发现一些错误,其中 TextWatcher 内部存在对尚未启动的 textField 的引用。虽然我是这么认为的

TextView textfield = new TextView(this);

在editText-field之前完成,并且该文本字段在editText-field之前添加到LinearLayout,如下所示:

linearLayout.addView(textfield);

很可能是新手错误...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    相关资源
    最近更新 更多