首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用Handler.postDelayed运行多个Runnables

使用Handler.postDelayed运行多个Runnables
EN

Stack Overflow用户
提问于 2012-10-30 02:24:41
回答 1查看 3.3K关注 0票数 0

我正在尝试让一段代码定期运行。

下面是我的代码:

代码语言:javascript
复制
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左右才开始执行它应该做的事情。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-10-30 02:44:56

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

首先,设置了一些类变量:

代码语言:javascript
复制
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;
    }
};

接下来,在onCreate()中初始化weightGainNumbers TextView。

最后,使用以下代码:

代码语言:javascript
复制
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);

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13127483

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档