错误提示:
android.view.ViewRootImpl$CalledFromWrondThreadException:Only the original thread that created a view hierarchy can touch its views;
错误原因:
Android 的UI是线程不安全的,因此不允许在子线程中进行UI操作。所有的UI操作都应该在主线程中进行。
错误代码:
package com.example.androidthreadtest;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=findViewById(R.id.text);
Button button = (Button)findViewById(R.id.change_text);
button.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.change_text:
new Thread(new Runnable() {
@Override
public void run() {
textView.setText("Hello World");
}
}).start();
break;
}
}
}
修改方式:
Android 提供了一套一部消息处理机制,新增一个Handler对象,用于监听消息。在子线程中需要对UI进行操作时,对主线程发送消息量,主线程接收到消息量之后,在主线程中进行UI操作。如下所示。
package com.example.androidthreadtest;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private TextView textView;
private static final int UPDATE_TEXT=1;
private Handler handler = new Handler(){
public void handleMessage(Message msg){
switch (msg.what){
case UPDATE_TEXT:
textView.setText("Nice to Meet You");
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=findViewById(R.id.text);
Button button = (Button)findViewById(R.id.change_text);
button.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.change_text:
new Thread(new Runnable() {
@Override
public void run() {
Message message = new Message();
message.what= UPDATE_TEXT;
handler.sendMessage(message);
}
}).start();
break;
}
}
}
网友评论