在某个Activity中,有一个TextView
名为timeText的变量,在打开Activity后经过3秒钟后需要对其进行更改。
这是我写的代码:
TextView timeText = (TextView) findViewById(R.id.tvTimeText);
Thread timer = new Thread() {
public void run() {
try {
sleep(3000);
timeText.setText("3");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
timer.start();
但这给了我这个错误:“无法在用不同方法定义的内部类中引用非最终变量timeText”
因此,我更改了TextView
to的修饰符,final
然后重试。但是,现在,此活动开始时,应用程序崩溃。
无法从非ui thrad更新ui
timeText.setText("3");
使用runOnUiThread
或Handler
。
runOnUiThread(new Runnable() {
public void run() {
timeText.setText("3");
}
});
您可以声明timeText
为实例变量,并且不需要final
修饰符。
TextView timerText;
protectected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
timeText = (TextView) findViewById(R.id.tvTimeText);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句