使用 Runnable & 更新 UIpostDelayed 不适用于计时器应用程序 [英] Updating UI with Runnable & postDelayed not working with timer app
问题描述
我已经查看了我可以找到的有关使其工作的所有讨论和线程,但事实并非如此.我有一个简单的计时器来更新文本视图(下面示例中的 mTimeTextField).mUpdateTimeTask run 方法正在正确执行(每秒),但 UI/文本字段未更新.
I have looked at every discussion and thread I can find on getting this to work but it is not. I have a simple timer that updates a text view (mTimeTextField in the example below). The mUpdateTimeTask run method is being executed correctly (every second) but the UI/text field is not being updated.
我有基于此处找到的信息的代码:
I have code based on the info found here:
http://android-developers.blogspot.com/2007/11/stitch-in-time.htmlhttp://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);
}
};
}
<小时>
根据一些建议,我尝试添加:
Per some suggestions, I have tried adding:
setContentView(mTimeLabel);
但是这会因为没有父视图的视图而崩溃.仅供参考,我确实有:
But this will crash complain about the view not having a parent. FYI, I do have a:
setContentView(R.layout.main);
调用我的onCreate()
.
推荐答案
替换
mHandler.postAtTime(this, 1000);
与
mHandler.postDelayed(this, 1000);
这篇关于使用 Runnable & 更新 UIpostDelayed 不适用于计时器应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!