【问题标题】:Display EditText value in another TextView after edit编辑后在另一个 TextView 中显示 EditText 值
【发布时间】:2012-12-27 19:21:43
【问题描述】:

我有一个 EditText,用户在其中输入一个字符串。编辑后,字符串显示在 TextView 中。我创建了一个名为 TextValidator 的自定义类,它实现了 TextWatcher,以满足 addTextChangedListener(TextWatcher watcher) 方法的参数。当我运行它时,当我按下一个字母输入到editText时,应用程序崩溃了。

在 MainActivity 中:

EditText editText1 = (EditText)findViewById(R.id.editText1);
editText1.addTextChangedListener(new TextValidator((EditText)findViewById(R.id.editText1)));

在我的 TextValidator 类中:

public class TextValidator extends Activity implements TextWatcher {
    private EditText editText;

    public TextValidator(EditText editText) {
        this.editText = editText;
    }

    public void validate(TextView textView, String text)
    {
        //I want to later check the string for valid format
    }

    final public void afterTextChanged(Editable s) {
        ((EditText)findViewById(R.id.textView1)).setText(editText.getText().toString());
        //validate(textView, text);
    }

【问题讨论】:

  • 致命异常:主要; java.lang.NullPointerException;它在这一行: final public void afterTextChanged(Editable s) { ((EditText)findViewById(R.id.textView1)).setText(editText.getText().toString()); }

标签: android textview android-edittext


【解决方案1】:

TextValidator 不扩展 Activity。

解决方案:

public class TextValidator implements TextWatcher {
    private Context mContext;
    private EditText mEditText;
    private TextView mTextView;

    public TextValidator(Context mContext) {
        this.mContext = mContext;
        EditText mEditText = (EditText)mContext.findViewById(R.id.editText1);
        TextView mTextView = (TextView)mContext.findViewById(R.id.textView1);
    }

    public void validate(TextView textView, String text)
    {
        //I want to later check the string for valid format
    }

    final public void afterTextChanged(Editable s) {
        mTextView.setText(mEditText.getText().toString());
        //validate(textView, text);
    }
    ....

【讨论】:

  • 那我怎么在 afterTextChanged 中调用 findViewById 呢?
  • 我把解决方案放在我的帖子里
  • 我使用了你的代码,同样的事情发生了(当我在 EditText 中按下一个字母或数字时,应用程序停止了)。
  • 不要忘记在 MainActivity 中进行更改:editText1.addTextChangedListener(new TextValidator(this));
  • 并分解这一行 mTextView.setText(mEditText.getText().toString());看看什么是空的。例如,您可以测试 if (mTextView == null) 或 if (mEditText == null) 或 if (mEditText.getText() == null)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-22
  • 1970-01-01
  • 2019-04-29
  • 2019-04-11
  • 2013-01-11
相关资源
最近更新 更多