:为什么不在子线程中更新UI时发生停止? 我搜索了很长时间但没有回答我。它发生在android 7和6上。
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private TextView textContent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textContent = findViewById(R.id.textContent);
Button changeTextButton = findViewById(R.id.change_text);
changeTextButton.setOnClickListener(this);
}
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.change_text:
new Thread(new Runnable() {
@Override
public void run() {
textContent.setText("Nice to meet you !");
}
}).start();
break;
default:
break;
}
}
答案 0 :(得分:0)
如果你想在另一个线程中更改UI,我的建议是使用runOnUiThread替换下面的代码 来自:
new Thread(new Runnable() {
@Override
public void run() {
textContent.setText("Nice to meet you !");
}
}).start();
到:
runOnUiThread(new Runnable() {
@Override
public void run() {
textContent.setText("Nice to meet you !");
}
});
答案 1 :(得分:0)
您无法从子/工作线程更改UI元素。只需执行以下操作:
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.change_text:
textContent.setText("Nice to meet you !");
break;
default:
break;
}
}
由于onClick()
将在主线程上执行