在onCreate()方法中,我正在以编程方式创建一个带有标记的TextEdit:
EditText et = new EditText(getApplicationContext());
et.setTag(field.getFieldId());
et.setBackgroundResource(R.drawable.textbox);
et.setTextColor(getResources().getColor(R.color.noir));
parentLayout.addView(et);
在afterTextChanged()方法中,我想检索该EditText标记以获取用户输入的文本。
我已经尝试过这段代码了,但是我得到了NullPointerException:
EditText et = (EditText) parentLayout.findViewWithTag("4249");
String strValue = et.getText().toString();
你能帮帮我吗?
谢谢。
答案 0 :(得分:0)
嗯,我自己找到了解决方案。
1)以编程方式创建EditText,设置自定义TextWatcher并将EditText添加到其中:
EditText et = new EditText(getApplicationContext());
et.setTag(field.getFieldId());
et.setBackgroundResource(R.drawable.textbox);
et.setTextColor(getResources().getColor(R.color.noir));
et.addTextChangedListener(new CustomTextWatcher(et));
2)创建自定义TextWatcher:
private class CustomTextWatcher implements TextWatcher{
private EditText editText;
private MyTextWatcher(EditText editText) {
this.editText = editText;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
String strValue = this.editText.getText().toString();
Log.d("afterTextChanged", strValue);
}
}
希望能帮助其他开发者。