gpt4 book ai didi

android - 使用 Runnable 和 postDelayed 更新 UI 不适用于计时器应用程序

转载 作者:IT老高 更新时间:2023-10-28 22:26:15 26 4
gpt4 key购买 nike

我已经查看了我可以找到的所有讨论和线程,但事实并非如此。我有一个简单的计时器来更新 TextView (下面示例中的 mTimeTextField)。 mUpdateTimeTask 运行方法正在正确执行(每秒),但 UI/文本字段未更新。

我有基于此处找到的信息的代码:

http://android-developers.blogspot.com/2007/11/stitch-in-time.html http://developer.android.com/resources/articles/timed-ui-updates.html

代码如下:

package com.something.handlertest;

import com.something.handlertest.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Test extends Activity {

private Handler mHandler = new Handler();
private int labelNo = 0;
private long currTime = 0L;
private long mStartTime = 0L;
TextView mTimeTextField;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

mTimeTextField = (TextView)findViewById(R.id.timeTextFieldl);

Button startButton = (Button)findViewById(R.id.start_button);
startButton.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
if (mStartTime == 0L) {
mStartTime = System.currentTimeMillis();
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 100);
}
}
});
}

private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
final long start = mStartTime;
//long millis = SystemClock.uptimeMillis() - start;
long millis = SystemClock.uptimeMillis();
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;

//setContentView(mTimeTextField); This will blow up if I use it

if (seconds < 10) {
mTimeTextField.setText("" + minutes + ":0" + seconds);
} else {
mTimeTextField.setText("" + minutes + ":" + seconds);
}

//mHandler.postAtTime(this,
// start + (((minutes * 60) + seconds + 1) * 1000));

mHandler.postAtTime(this, 1000);
}
};

}

根据一些建议,我尝试添加:

setContentView(mTimeLabel);

但这会崩溃提示 View 没有父级。仅供引用,我确实有一个:

setContentView(R.layout.main);

调用我的onCreate()

最佳答案

替换

mHandler.postAtTime(this, 1000);

mHandler.postDelayed(this, 1000);

关于android - 使用 Runnable 和 postDelayed 更新 UI 不适用于计时器应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3765161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com