我正在尝试定期运行一段代码 这是我的代码:
int endTime = 52;
final double[] weights = new double[endTime];
for (int j = 0; j < endTime; j++) {
final int k = j;
newWeight = i.integrate(getCarbs(), getProt(), getFat(), newWeight,
height, age, PAL, gender, 7);
double percentChange = (newWeight - weight);
percentChange = percentChange * 100 / weight;
if(percentChange <-100){
percentChange = -100;
}
weights[j] = percentChange;
final DecimalFormat twoDForm = new DecimalFormat("0.00");
final Handler h = new Handler();
int time = 300*(j);
Runnable r = new Runnable() {
public void run() {
((TextView) findViewById(R.id.weightGainNumbers))
.setText("Week:\t" + (k + 1) + "\nWeight Change:\t"
+ twoDForm.format(weights[k]) + "%");
animate(weights[Math.abs(k - 1)], weights[k], false);
}
};
h.postDelayed(r, time);
}
动画只需100毫秒。然而,当我运行它时,应用程序挂起,并且只开始执行它应该在j = 15周围的内容。有人知道这里有什么问题吗?
答案 0 :(得分:1)
您正在循环的每次迭代中执行不必要的工作,例如在您可以简单地重用一个时创建新的DecimalFormats。此外,您只需要一个处理程序,每个View都有一个处理程序。总而言之,这应该更加顺利。
首先,设置一些类变量:
final DecimalFormat twoDForm = new DecimalFormat("0.00");
TextView weightGainNumbers;
int weightGainIndex = 0;
final double[] weights;
Runnable r = new Runnable() {
public void run() {
weightGainNumbers.setText("Week:\t" + (weightGainIndex + 1) + "\nWeight Change:\t"
+ twoDForm.format(weights[weightGainIndex]) + "%");
if(weightGainIndex > 0)
animate(weights[Math.abs(weightGainIndex - 1)], weights[weightGainIndex], false);
// This animation is a guess, but you get the idea...
else
animate(0, weights[weightGainIndex], false);
weightGainIndex++;
// Call the next animation or reset the index for next time
if(weightGainIndex < weights.length)
weightGainNumbers.postDelayed(r, 300);
else
weightGainIndex = 0;
}
};
接下来,初始化weightGainNumbers
中的onCreate()
TextView。
最后,使用此:
int endTime = 52;
weights = new double[endTime];
for (int j = 0; j < endTime; j++) {
newWeight = i.integrate(getCarbs(), getProt(), getFat(), newWeight,
height, age, PAL, gender, 7);
weights[j] = Math.max(percentChange * 100 / (newWeight - weight), -100);
}
weightGainNumbers.post(r);
如果您有任何具体问题,请与我们联系。