为什么这段代码有效?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("onCreate", Thread.currentThread().toString());
textView = (TextView) findViewById(R.id.textView);
imageView = (ImageView) findViewById(R.id.imageView);
HandlerThread thread = new HandlerThread("myHandlerThread");
thread.start();
mUiHandler = new Handler(thread.getLooper());
mUiHandler.post(new Runnable() {
@Override
public void run() {
Log.i("Thread: ", Thread.currentThread().toString());
Toast.makeText(getApplicationContext(), "Hello Cats!", Toast.LENGTH_SHORT).show();
textView.setText("Hello Cats");
imageView.setImageResource(R.mipmap.ic_launcher);
}
});
}
我从某个地方读到唯一可以与 UI 对象通信的线程是 UI 线程,或者我错过了一些东西
我有一些研究,但还没有找到答案,请帮助,非常感谢你们。
这是我从日志中得到的
10-13 18:47:42.888 23841-23841/th.co.me.sampleapp I/onCreate: Thread[main,5,main]
10-13 18:47:42.891 23841-24041/th.co.me.sampleapp I/Thread:: Thread[myHandlerThread,5,main]
更新 1
我从@nshmura 尝试了这段代码,但发生了错误,现在让我很困惑
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HandlerThread thread = new HandlerThread("myHandlerThread");
thread.start();
mUiHandler = new Handler(thread.getLooper());
mUiHandler.post(new Runnable() {
@Override
public void run() {
Log.i("Thread: ", Thread.currentThread().toString());
Toast.makeText(getApplicationContext(), "Hello Cats!", Toast.LENGTH_SHORT).show();
textView.setText("Hello Cats");
imageView.setImageResource(R.mipmap.ic_launcher);
}
});
}
});
android.view.ViewRootImpl$CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能接触其视图。