Single TextWatcher for multiple EditTexts?
I have multiple(12) EditTexts in m开发者_高级运维y activity in pairs of 2. I want to do an action for each pair when the text in them changes. Do I need to have 6 different TextWatchers or is there a way to use the same one for or and do some kind of switch?
You can attach the same TextWatcher watch to each EditText. Depending on what you need to do you may need to create you implementation of TextWatcher with some context.
I needed this so i made a reusable one ...i extended off textwatcher class so i could pass in the view i want to watch.
/**
*
* A TextWatcher which can be reused
*
*/
public class ReusableTextWatcher implements TextWatcher {
private TextView view;
// view represents the view you want to watch. Should inherit from
// TextView
private GenericTextWatcher(View view) {
if (view instanceof TextView)
this.view = (TextView) view;
else
throw new ClassCastException(
"view must be an instance Of TextView");
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i,
int before, int after) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int before,
int count) {
int id = view.getId();
if (id == R.id.someview){
//do the stuff you need to do for this particular view
}
if (id == R.id.someotherview){
//do the stuff you need to do for this other particular view
}
}
@Override
public void afterTextChanged(Editable editable) {
}
}
then to use it i do something like this to register it:
myEditText.addTextChangedListener(new ReusableTextWatcher(myEditText));
精彩评论