0

我正在安排一个简单的任务,应该在 4 秒内更新一个文本字段。

然而,每次这被称为活动暂停并且在我重新启动活动之前不会在文本字段中显示值。

 private void showDelayedValue() {

    Runnable longRunningTask = new Runnable() {
        public void run() {

        int randomVal = randomNumberGenerator.nextInt(30 - -10) - 10; //random number between -10 and 30
        String randomValStr = Integer.toString(randomVal);

            Log.i(this.getClass().getSimpleName(),
                "FIRED startScheduler: " + randomValStr);

        theFieldOnScreenTV.setText(randomTempStr);

        }
    };
    //show the value in 2 seconds
    scheduledTaskExecutor.schedule(longRunningTask, 4, TimeUnit.SECONDS);

    }

日志显示:

FIRED startScheduler: 4

但不更新TextView theFieldOnScreenTV

而是 在 LogCat 中显示onPause后立即调用。Fired startScheduler:

非常感谢!

编辑:

按照亚历克斯的方法,这对我有用:

private void showDelayedValue() {
    int randomX = randomNumberGenerator.nextInt(30 - -10) - 10; 
    final String randomXStr = Integer.toString(randomX);
    final Runnable updateFieldR = new Runnable() {
        public void run() {
        theFieldOnScreenTV.setText(randomXStr);
        }
    };

    Runnable longRunningTask = new Runnable() {
        public void run() {
        theFieldOnScreenTV.post(updateFieldR);

        }
    };
    scheduledTaskExecutor.schedule(longRunningTask, 4, TimeUnit.SECONDS);

    }
4

2 回答 2

1

代替

theFieldOnScreenTV.setText(randomTempStr); 

尝试

theFieldOnScreenTV.post(new Runnable() { theFieldOnScreenTV.setText(randomTempStr); } );
于 2012-10-29T15:24:39.320 回答
0

尝试使用处理程序。

Handler handler = new Handler();
handler.post(new Runnable() {

@Override
public void run() {

theFieldOnScreenTV.setText(randomTempStr);          
    }
});
于 2012-10-29T15:57:10.833 回答