1

我试图在按下按钮后以五秒的时间间隔更新 TextView,但是当应用程序运行时,TextView 将只显示它正在运行的循环的最后一个值。

这是我正在尝试的:

private Runnable textUpdate = new Runnable() {
    public void run() {
        textOutput = (TextView)findViewById(R.id.textOutput);

        textOutput.setText("Reading Number " + (rIndex+1) + "\n");
        textOutput.append(sensorTime[rIndex] + "\n");
        textOutput.append("Value: " + rPoint.getValue() + "\n");
    }
};

...

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mHandler = new Handler();

    TextView textOutput = (TextView) findViewById(R.id.textOutput);
    textOutput.setText("Simulation output:\n");

    Button button03 = (Button) findViewById(R.id.button03);
    button03.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            for(int i = 0; i < index; i++) {
                rIndex = i;
                rPoint = dp[i];

                mHandler.postDelayed(textUpdate, 5000);
            }
        }
    });

}

无法理解为什么只有我试图输出的信息的最后一个值显示在 TextView 中。

任何帮助表示赞赏。

4

2 回答 2

3

我看到的问题是您的最后一行代码:

mHandler.postDelayed(textUpdate, 5000);

您以 5000 毫秒的时间发布所有更新,每个更新都以毫秒为间隔(与手机循环的速度一样快)。

试试这个:

mHandler.postDelayed(textUpdate, i * 5000);
于 2012-04-23T18:52:38.573 回答
0

您可以再次制作可运行的帖子。

private Runnable textUpdate = new Runnable() {
    public void run() {
        textOutput = (TextView)findViewById(R.id.textOutput);

        textOutput.setText("Reading Number " + (rIndex+1) + "\n");
        textOutput.append(sensorTime[rIndex] + "\n");
        textOutput.append("Value: " + rPoint.getValue() + "\n");

        mHandler.postDelayed(this, 5000);
    }
};

然后删除 onPause 中的所有消息

于 2012-04-23T18:53:11.547 回答