单个TextWatcher用于多个EditTexts?

时间:2011-02-27 00:13:56

标签: android android-edittext textwatcher

我的活动中有多个(12)EditTexts,成对为2.我想在每个对中的文本发生变化时为每个对执行操作。我是否需要有6种不同的TextWatchers,或者是否有办法使用相同的或者进行某种切换?

2 个答案:

答案 0 :(得分:2)

您可以将相同的TextWatcher观看附加到每个EditText。根据您的需要,您可能需要使用某些上下文创建TextWatcher的实现。

答案 1 :(得分:1)

我需要这个,所以我做了一个可重复使用的...我延伸了textwatcher课程,所以我可以通过我想看的视图。

/**
 *  
 * 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) {

    }
}

然后使用它我做这样的事情来注册它:

myEditText.addTextChangedListener(new ReusableTextWatcher(myEditText));