本文介绍了如何使用单TextWatcher多个EditTexts?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个的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));

⋮

这篇关于如何使用单TextWatcher多个EditTexts?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 00:11