android – 如何使用单个TextWatcher多个EditTexts?

我有三个EditText小部件在我的视图布局。有没有办法使用一个单一的TextWatcher所有三个EditTexts?
我刚遇到这个问题。我通过创建一个TextWatcher的内部类实现来解决它,它使用一个View作为参数。然后,在方法实现中,只需打开视图,看看Editable是来自哪个:

//Declaration
private class GenericTextWatcher implements TextWatcher{

    private View view;
    private GenericTextWatcher(View view) {
        this.view = view;
    }

    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

    public void afterTextChanged(Editable editable) {
        String text = editable.toString();
        switch(view.getId()){
            case R.id.name:
                model.setName(text);
                break;
            case R.id.email:
                model.setEmail(text);
                break;
            case R.id.phone:
                model.setPhone(text);
                break;
        }
    }
}

& vellip;

// Usage:

name = (EditText) findViewById(R.id.name);
name.setText(model.getName());
name.addTextChangedListener(new GenericTextWatcher(name));

email = (EditText) findViewById(R.id.email);
email.setText(model.getEmail());
email.addTextChangedListener(new GenericTextWatcher(email));

phone = (EditText) findViewById(R.id.phone);
phone.setText(model.getPhone());
phone.addTextChangedListener(new GenericTextWatcher(phone));

& vellip;

http://stackoverflow.com/questions/5702771/how-to-use-single-textwatcher-for-multiple-edittexts

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:android – 如何使用单个TextWatcher多个EditTexts?