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 を作成するなど、ループの各反復で不要な作業を実行しています。また、必要なハンドラーは 1 つだけで、すべてのビューには既にハンドラーがあります。全体として、これはよりスムーズに実行されるはずです。

まず、いくつかのクラス変数を設定します。

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でTextView を初期化し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 に答える