I would like to use the code below to set up an array of listeners
public void setListeners() {
final int k ;
for (k=0; k<6; k++) {
mNumberView[k].addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mSprintHrs[k] = calcSprint(0, s);
String mSH = String.format("%.1f", mSprintHrs[k]);
mSprintView[k].setText(mSH);
calcTotal();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
I get a compiler error on k++ in the for statement
Value k might already been assigned to
Any workaround?
The error is because you're trying to modify a final
variable. If you need to access a mutable variable inside an anonymous subclass, you'll have to copy it to a final
variable:
for (int i=0; i<6; i++) {
final int k = i;
A possibly cleaner workaround would be to extract the loop body to a separate method with a final
parameter.