我正在尝试让一个基本计时器在 Android 上工作,并且我在 onCreate() 方法中有以下代码:
editText = (EditText) findViewById(R.id.edit_message);
Timer time = new Timer();
time.schedule(new TimerTask() {
public void run() {
timesince++;
editText.setText("Timeran:"+timesince);
Log.d("TIMER", "TimerTask run");
}}, 0, 1000);
所以希望它会用一个增加的值(timesince)来更新文本框 - 这是在程序顶部声明的,以及editText ...
但是,(尽管我没有遇到编译问题)当我在模拟器上运行它时它根本不起作用。应用程序显示“blahblahblah 已停止工作......”
我做错了定时器吗?我错过了什么?
非常感谢。
(如果删除此代码,PS App 可以正常工作,所以我知道这部分存在问题。)
编辑:我相信这是我的 logcat 输出,对不起文字墙:
10-11 03:40:49.260: E/AndroidRuntime(561): FATAL EXCEPTION: Timer-0
10-11 03:40:49.260: E/AndroidRuntime(561): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
10-11 03:40:49.260: E/AndroidRuntime(561): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:3939)
10-11 03:40:49.260: E/AndroidRuntime(561): at android.view.ViewRootImpl.invalidateChild(ViewRootImpl.java:714)
10-11 03:40:49.260: E/AndroidRuntime(561): at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:763)
10-11 03:40:49.260: E/AndroidRuntime(561): at android.view.ViewGroup.invalidateChild(ViewGroup.java:4012)
10-11 03:40:49.260: E/AndroidRuntime(561): at android.view.View.invalidate(View.java:8454)
10-11 03:40:49.260: E/AndroidRuntime(561): at android.widget.TextView.invalidateCursor(TextView.java:4319)
10-11 03:40:49.260: E/AndroidRuntime(561): at android.widget.TextView.spanChange(TextView.java:7670)
10-11 03:40:49.260: E/AndroidRuntime(561): at android.widget.TextView$ChangeWatcher.onSpanAdded(TextView.java:8020)
10-11 03:40:49.260: E/AndroidRuntime(561): at android.text.SpannableStringBuilder.sendSpanAdded(SpannableStringBuilder.java:898)
10-11 03:40:49.260: E/AndroidRuntime(561): at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:614)
10-11 03:40:49.260: E/AndroidRuntime(561): at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:520)
10-11 03:40:49.260: E/AndroidRuntime(561): at android.text.Selection.setSelection(Selection.java:76)
10-11 03:40:49.260: E/AndroidRuntime(561): at android.text.Selection.setSelection(Selection.java:87)
10-11 03:40:49.260: E/AndroidRuntime(561): at android.text.method.ArrowKeyMovementMethod.initialize(ArrowKeyMovementMethod.java:302)
10-11 03:40:49.260: E/AndroidRuntime(561): at android.widget.TextView.setText(TextView.java:3244)
10-11 03:40:49.260: E/AndroidRuntime(561): at android.widget.TextView.setText(TextView.java:3110)
10-11 03:40:49.260: E/AndroidRuntime(561): at android.widget.EditText.setText(EditText.java:78)
10-11 03:40:49.260: E/AndroidRuntime(561): at android.widget.TextView.setText(TextView.java:3085)
10-11 03:40:49.260: E/AndroidRuntime(561): at com.example.cultivation.MainActivity$1.run(MainActivity.java:54)
10-11 03:40:49.260: E/AndroidRuntime(561): at java.util.Timer$TimerImpl.run(Timer.java:284)