如何使用TextWatcher获得几个EditText的总和结果?

时间:2014-01-27 18:11:40

标签: android android-edittext textwatcher

我如何才能在TextView中获得几个EditText的总和结果,因此TextWatcher将它们添加到离开时,因为它们将数字放在EditText中

    edit1.addTextChangedListener(mTextEditorWatcher);
    edit2.addTextChangedListener(mTextEditorWatcher);
    edit3.addTextChangedListener(mTextEditorWatcher);
}

private final TextWatcher  mTextEditorWatcher = new TextWatcher() {
    public void beforeTextChanged(CharSequence s, int start, int count, int after)
    {

    }

    public void onTextChanged(CharSequence s, int start, int before, int count)
    {

    }

    public void afterTextChanged(Editable s)
    {
        String change;
        int num= 0;
        int n = 0;
        change = s.toString();
        num =  Integer.parseInt(change);
        n = n + num;
        Posi.setText(n); 
    }
};

1 个答案:

答案 0 :(得分:1)

您的TextWatcher需要知道需要总结的EditTexts。例如,您可以在构造函数中传递它们。

private class MyTextWatcher implements TextWatcher {
    private List<EditText> editTexts;

    public MyTextWatcher(EditText et1, EditText et2, EditText et3){
        ....
    }

    // or
    public MyTextWatcher(List<EditText> editTexts){
        this.editTexts = editTexts;
    }

    ....
}