我有一个 textview,我可以用它来显示倒数计时器。我想使用带有 Runnable 接口的 Thread 类。
我为此编写了以下代码,但它给出了运行时错误不幸的是 ThreadApp 已停止
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity implements Runnable
{
TextView tvTimer;
Thread timerThread;
int time=30;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvTimer =(TextView)findViewById(R.id.textView1);
timerThread= new Thread(this);
timerThread.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void run()
{
try
{
Thread.sleep(1000);
tvTimer.setText((String.valueOf(time)).toString());
time--;
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
同时当我删除tvTimer.setText((String.valueOf(time)).toString()); 它工作正常。谁能给我解决方案。我是安卓新手。