无需重复代码的多个 addTextChangedListeners

Multiple addTextChangedListeners without duplicating code

我目前有 24 个 EditText 在我的一个屏幕上,我需要听众在其中一个发生变化时更新总数,但我不确定如何在没有 24 个单独的情况下设置它听众的代码片段。答案可能真的很明显,但我不太明白,我发现了一些类似的问题,但我自己却无法解决。

这是我的代码:

 private void loadPage() {
    round1Boxer1Input = (EditText) findViewById(R.id.round1Boxer1Input);
    totalBoxer1Text = (TextView) findViewById(R.id.totalBoxer1Text);
    round2Boxer1Input = (EditText) findViewById(R.id.round2Boxer1Input);
    round3Boxer1Input = (EditText) findViewById(R.id.round3Boxer1Input);
    round4Boxer1Input = (EditText) findViewById(R.id.round4Boxer1Input);
    round5Boxer1Input = (EditText) findViewById(R.id.round5Boxer1Input);
    round6Boxer1Input = (EditText) findViewById(R.id.round6Boxer1Input);
    round7Boxer1Input = (EditText) findViewById(R.id.round7Boxer1Input);
    round8Boxer1Input = (EditText) findViewById(R.id.round8Boxer1Input);
    round9Boxer1Input = (EditText) findViewById(R.id.round9Boxer1Input);
    round10Boxer1Input = (EditText) findViewById(R.id.round10Boxer1Input);
    round11Boxer1Input = (EditText) findViewById(R.id.round11Boxer1Input);
    round12Boxer1Input = (EditText) findViewById(R.id.round12Boxer1Input;)

    final EditText[] boxer1List = {round1Boxer1Input, round2Boxer1Input, round3Boxer1Input, round4Boxer1Input,
            round5Boxer1Input, round6Boxer1Input, round7Boxer1Input, round8Boxer1Input, round9Boxer1Input,
            round10Boxer1Input, round11Boxer1Input, round12Boxer1Input};

    round1Boxer1Input.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            totalBoxer1Text.setText(String.valueOf(addRoundsBoxer1(boxer1List)));
        }
    });
}

就目前而言,我认为我必须让其中的 24 个听众成为听众,我认为这不是一个好方法。

对于这种特定情况,为什么不采用一种采用 EditText 并将 TextWatcher 应用于它的方法?例如

protected void applyTextWatcher(EditText roundInput, TextView boxerTotalText, EditText[] roundInputList){
    roundInput.addTextChangedListener(new TextWatcher() {
        ....
        @Override
        public void afterTextChanged(Editable editable) {
          boxerTotalText.setText(String.valueOf(sumRounds(roundInputList)));
        }
    });
}

您可以通过以下方式使用:

for(EditText roundInput : boxer1List)
    applyTextWatcher(roundInput, totalBoxer1Text, boxer1List);

尽管如此,您仍将在此处复制大量代码,而且它不是很灵活(即 more/less 轮将意味着部署代码更改),您可能需要更面向对象的方法。例如

您可以使用

而不是没有实际引用的 EditText 列表
public class Round {
    int roundNumber;

    int boxer1Score;
    int boxer2Score;
}

public class RoundViewHolder {
    Round round;

    EditText boxer1Input;
    EditText boxer2Input;
}

然后,您将有一个 List<RoundViewHolder> 可以使用,而不仅仅是 EditText,它直接链接到 Round,这将帮助您根据回合数动态生成 EditText实际发生了。

这是一些伪代码,不是您需要的所有内容,但应该能为您指明正确的方向。