我有一个EditText,用户输入一个字符串。编辑后,字符串将显示在TextView中。我创建了一个名为TextValidator的自定义类,它实现了TextWatcher,以满足addTextChangedListener(TextWatcher观察者)方法的参数。当我运行它时,当我按下一个字母输入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);
}
答案 0 :(得分:2)
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);
}
....