我做了一些研究,并尝试了一些代码,包括来自Android postDelayed Handler Inside a For Loop?的以下代码。
final Handler handler = new Handler();
int count = 0;
final Runnable runnable = new Runnable() {
public void run() {
// need to do tasks on the UI thread
Log.d(TAG, "runn test");
if (count++ < 5)
handler.postDelayed(this, 5000);
}
};
// trigger first time
handler.post(runnable);
但是count变量将显示错误,因为它是在内部类中访问的。我该如何解决这个问题?
答案 0 :(得分:0)
变量“计数”是从内部类内部访问的,需要是最终的或实际上是最终的
您需要将count
转换为最终的一个元素数组
final Handler handler = new Handler();
final int[] count = {0}; //<--changed here
final Runnable runnable = new Runnable() {
public void run() {
// need to do tasks on the UI thread
Log.d(TAG, "runn test");
if (count[0]++ < 5) //<--changed here
handler.postDelayed(this, 5000);
}
};
// trigger first time
handler.post(runnable);