获取以编程方式创建的视图标签
get view tag created programmatically
在 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();
你能帮帮我吗!!
谢谢。
嗯,我自己找到了解决办法。
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);
}
}
希望对其他开发者有所帮助。
在 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();
你能帮帮我吗!!
谢谢。
嗯,我自己找到了解决办法。
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);
}
}
希望对其他开发者有所帮助。