我怎样才能在这里增加我的计数器:
private void startTimer() {
int i = 0;
final Timer timer = new Timer();
final TimerTask task = new TimerTask() {
@Override
public void run() {
if(preferences.getBoolean(IS_RUNNING_KEY, false))
{
final int k = i++; //i must declared final error
runOnUiThread(new Runnable() {
@Override
public void run() {
timeCounter.setText(""+k);
Log.d("DTAG","K: "+k);
}
});
} else {
timer.cancel();
timer.purge();
}
}
};
timer.schedule(task, 1000);
}
答案 0 :(得分:1)
您必须将i
移出功能范围。然后它不必被声明为final,你可以改变它。将您的代码更改为此
private int i = 0;
private void startTimer() {
final Timer timer = new Timer();
final TimerTask task = new TimerTask() {
@Override
public void run() {
if(preferences.getBoolean(IS_RUNNING_KEY, false))
{
final int k = i++;
runOnUiThread(new Runnable() {
@Override
public void run() {
timeCounter.setText(""+k);
Log.d("DTAG","K: "+k);
}
});
} else {
timer.cancel();
timer.purge();
}
}
};
timer.schedule(task, 1000);
}