-4

如果我在任何一个编辑文本中更改它的总和并显示在 Textview 中,我的应用程序中现在有 10 个 EditText

但是我如何使用更少的代码

或者我为所有 EditText 处理所有 EditText Onchange 事件

我尝试使用 TextWatcher 观看所有编辑文本,但我如何获得所有编辑文本

private TextWatcher filterTextWatcher = new TextWatcher() {

    public void afterTextChanged(Editable s) {
        //Do your stuff
        String text;


    }

    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        // do your stuff
    }

    public void onTextChanged(CharSequence s, int start, int before,
            int count) {
        // do your stuff

    }

};

请帮助

4

1 回答 1

1

一种简单的方法是获取包含所有 EditTexts 的父视图组,遍历其子视图并执行任何操作:

ViewGroup editTextsContainer = (ViewGroup) findViewById(R.id.editTexts_container);
int sum = 0;
int i = edtTextsContainer.getChildCount();
for(int j=0;j<i;j++) {
    View child = editTextsContainer.getChildAt(i);
    if(child instanceof EditText) {
        sum += Integer.parseInt((EditText)child).getText());
        // handle cases where edittext text is not numbers, or set the inputType in xml to avoid
    }
}
myTextView.setText(""+sum);

代码没有经过测试,只是给你一个粗略的想法。

于 2013-04-18T12:08:53.873 回答