0

我试图让一段代码定期运行。
这是我的代码:

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 左右做的事情。有人知道这里出了什么问题吗?

4

1 回答 1

1

您在循环的每次迭代中都在执行不必要的工作,例如在您可以简单地重用一个时创建新的 DecimalFormats。此外,您只需要一个处理程序,每个视图都已经有一个处理程序。所有这些都应该运行得更顺利。

首先,设置一些类变量:

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().

最后,使用这个:

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);

如果您有任何具体问题,请告诉我。

于 2012-10-29T18:44:56.173 回答