我有一个文本视图。我想在单击按钮 1 秒后更新其文本(附加“1”)。
public class HaikuDisplay extends Activity {
Method m;
Timer t;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = new Timer();
m = HaikuDisplay.class.getMethod("change");
}
//Event handler of the button
public void onRefresh(View view)
{
//To have the reference of this inside the TimerTask
final HaikuDisplay hd = this;
TimerTask task1 = new TimerTask(){
public void run(){
/*
* I tried to update the text here but since this is not the UI thread, it does not allow to do so.
*/
//Calls change() method
m.invoke(hd, (Object[])null);
}
};
t.schedule(task1, 1000);
}
public void change()
{
//Appends a "1" to the TextView
TextView t = (TextView)findViewById(R.id.textView1);
t.setText(t.getText() + "1");
}
//Event handler of another button which updates the text directly by appending "2".
//This works fine unless I click the first button.
public void onRefresh1(View view)
{
TextView t = (TextView)findViewById(R.id.textView1);
t.setText(t.getText() + "2");
}
}
考虑处理所有异常。
第一次点击时,m.invoke
给出InvocationTargetException
. 但是它change()
在没有任何异常的情况下连续调用该方法(通过日志记录验证)。但它不会更新文本。我哪里错了?
此外,我在调试器中看到每次单击按钮时都会创建一个新线程。那也行。但是为什么它不删除以前的线程,尽管它们的执行已经完成?