我正在尝试更新TextView
。
这个方法位于我的主类中,在onCreate()
中调用;
我试过使用runOnUiThread()
,但没有用。
一旦达到30秒,并且它尝试更新TextView,它就会崩溃!
任何帮助都是感激不尽的:
public void updateDisplay() {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
int mHour = c.get(Calendar.HOUR_OF_DAY);
int mMinute = c.get(Calendar.MINUTE);
textView3.setText(new StringBuilder()
// Month is 0 based so add 1
.append(mDay).append("/")
.append(mMonth + 1).append("/")
.append(mYear)
.append(" - ")
.append(mHour)
.append(":")
.append(mMinute));
}
}
,0,30000);//Update text every 30 seconds
}
而错误是:
E/AndroidRuntime: FATAL EXCEPTION: Timer-0
Process: ggrgroup.com.workforceapp, PID: 21879
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7261)
at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:1100)
at android.view.ViewGroup.invalidateChild(ViewGroup.java:5219)
at android.view.View.invalidateInternal(View.java:12900)
at android.view.View.invalidate(View.java:12860)
at android.view.View.invalidate(View.java:12844)
at android.widget.TextView.checkForRelayout(TextView.java:7459)
at android.widget.TextView.setText(TextView.java:4390)
at android.widget.TextView.setText(TextView.java:4247)
at android.widget.TextView.setText(TextView.java:4222)
at ggrgroup.com.workforceapp.MainActivity$1.run(MainActivity.java:77)
at java.util.Timer$TimerImpl.run(Timer.java:284)
3条答案
按热度按时间bn31dyow1#
mzsu5hc02#
错误线程异常:只有创建视图层次结构的原始线程可以访问其视图。
因为您在线程中编辑了textView 3
试试看:
{定时器=新定时器();
}
lokaqttq3#
使用@Ezio所述的处理程序
Looper.getMainLooper()
将在UI线程上运行runnablehandler.postDelayed(this, 30000);
将使其每30秒重复一次