如何使用单TextWatcher多个EditTexts?多个、如何使用、TextWatcher、EditTexts

2023-09-12 22:07:47 作者:乍见之欢

我有三个的EditText 小部件在我看来布局。有没有一种方法使用一个 TextWatcher 所有三个 EditTexts

I have three EditText widgets in my view layout. Is there a way to use a single TextWatcher for all three EditTexts?

推荐答案

我只是遇到了这个问题。我通过创建一个内部类实现TextWatcher那需要一个视图作为参数解决了这个问题。然后,在该方法的实施,只是打开视图以查看哪一个可编辑是来自:

I just encountered this problem. I solved it by creating an inner class implementation of TextWatcher that takes a View as an argument. Then, in the method implementation, just switch on the view to see which one the Editable is coming from:

//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;
        }
    }
}

⋮

// 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));

⋮