问题描述
我想测试的用户界面和Timer类的可能性。所以,我想下面的练习:
I'm trying to test UI and Timer class possibilities. So I tried the following exercise:
=== TestTimerActivity.java ===
=== TestTimerActivity.java ===
package com.tvt.TestTimer;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.util.Timer;
import java.util.TimerTask;
public class TestTimerActivity extends Activity {
TextView _tv;
Timer _t;
int _count = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//
// _tv = (TextView) getWindow().getDecorView().findViewById( R.id.TextViewTime );
_tv = (TextView) findViewById( R.id.TextViewTime );
UpdateTime(); // Completes OK
_t = new Timer();
_t.scheduleAtFixedRate( new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
_count++;
UpdateTime(); // Fails
}
}, 1000, 1000 );
}
protected void UpdateTime() {
_tv.setText( "" + _count );
}
}
=== TestTimerActivity.java ===
=== TestTimerActivity.java ===
=== ===的main.xml
=== main.xml ===
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:gravity="center_horizontal" android:layout_height="wrap_content" android:layout_gravity="center" android:text="@string/header" android:id="@+id/TestViewHeader" android:textStyle="bold"/>
<TextView android:layout_height="wrap_content" android:id="@+id/TextViewTime" android:layout_width="match_parent" android:layout_gravity="center_horizontal" android:gravity="center_horizontal" android:text="-"></TextView>
</LinearLayout>
=== ===的main.xml
=== main.xml ===
在第一个录入调用(从的onCreate)完成OK但从TimerTask的同一电话:: run()的失败给消息TestTimer类意外停止。
The very first UpdateTime call (from onCreate) completes OK but the same call from TimerTask::run() fails giving the message "TestTimer class has stopped unexpectedly".
你知道吗?哪里是我的错吗?
Any idea? Where is my fault?
-
SY,TVT
--
SY, TVT
推荐答案
请在UpateTime()在UI线程上运行。
Do that UpateTime() operation on the UI thread.
protected void UpdateTime()
{
runOnUiThread(new Runnable()
{
public void run()
{
_tv.setText( "" + _count );
}
});
}
希望可以解决您的问题。
Hopefully resolves your problem.
这篇关于从错误的TimerTask的run方法更新的TextView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!