CalledFromWrongThreadException: Only the original thread that created a view
程序员文章站
2022-04-01 15:50:34
...
private void btnfinishClick(View v)
{
new Thread(new MyRunnable()).start();
}
class MyRunnable implements Runnable{
@Override
public void run()
{
try
{
setContentView(R.layout.activity_call_finish);
TextView tv = (TextView)findViewById(R.id.name);
tv.setText(number);
TextView prompt = (TextView)findViewById(R.id.prompt);
prompt.setText("通话结束");
TextView ct = (TextView)findViewById(R.id.call_chronometer);
ct.setText(call_chronometer.getText());
Thread.sleep(1000);
myHandler.sendEmptyMessage(1);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
在通话结束时跳转到一个过渡界面,而上面的写法是将更新UI的代码写入到UI子线程中,所以会报错:
CalledFromWrongThreadException: Only the original thread that created a view
正确的做法时
将:
setContentView(R.layout.activity_call_finish);
TextView tv = (TextView)findViewById(R.id.name);
tv.setText(number);
TextView prompt = (TextView)findViewById(R.id.prompt);
prompt.setText("通话结束");
TextView ct = (TextView)findViewById(R.id.call_chronometer);
ct.setText(call_chronometer.getText());
代码从子线程中提到btnfinishClick()里面,这样就不会报错了