【发布时间】:2016-11-09 20:38:49
【问题描述】:
我目前在我的一个屏幕上有 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 个这样的听众,我认为这不是一个好方法。
【问题讨论】:
-
创建一个实现 TextWatcher 的内部类,并在 costructor 中获取一个视图(您的 EditText)或资源 ID。在 afterTextChanged 方法中,您只需访问 View 或 Ressource ID 并决定做什么。相关:stackoverflow.com/questions/22866060/…
标签: java android textchanged