[英]Able to Update UI from background thread
As per my basic knowledge, We cannot update UI from worker threads. 根据我的基本知识,我们无法从工作线程更新UI。 I tried this below code, it is able to update from async task to UI.
我尝试下面的代码,它能够从异步任务更新到UI。
Is my understanding wrong. 我的理解是错误的。 From this code i am getting impression that we can update UI from background thread.
从这段代码中,我得到的印象是我们可以从后台线程更新UI。 Only in case of toast it is failing.
仅在烤面包的情况下会失败。 Remaining all UI operation i am able to do from background thread.
剩下的所有UI操作我都可以从后台线程执行。 Can someone clear me this ?
有人可以清除这个吗?
Main Activity 主要活动
public class MainActivity extends AppCompatActivity {
TextView textView;
SeekBar progressBar;
ConstraintLayout constraintLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.txtview);
progressBar = findViewById(R.id.prg);
constraintLayout = findViewById(R.id.con);
AsyncTaskThread asyncTaskThread = new AsyncTaskThread();
asyncTaskThread.execute();
}
public class AsyncTaskThread extends AsyncTask {
@Override
protected Object doInBackground(Object[] objects) {
textView.setText("Hi Heloo");
progressBar.setIndeterminate(false);
progressBar.setMax(100);
progressBar.setProgress(50);
return null;
}
}
}
In onCreate
method, your views are not be lay out and visible on screen yet, they are just java objects in memory, at that time AsyncTask
just set properties on them. 在
onCreate
方法中,您的视图尚未布局并在屏幕上可见,它们只是内存中的Java对象,当时AsyncTask
只是在其上设置属性。
Now change your code to 现在将您的代码更改为
public class MainActivity extends AppCompatActivity {
TextView textView;
SeekBar progressBar;
ConstraintLayout constraintLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.txtview);
progressBar = findViewById(R.id.prg);
constraintLayout = findViewById(R.id.con);
// TODO: Add this code
textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// At this time, this view is lay out and visible on screen.
AsyncTaskThread asyncTaskThread = new AsyncTaskThread();
asyncTaskThread.execute();
}
});
}
public class AsyncTaskThread extends AsyncTask {
@Override
protected Object doInBackground(Object[] objects) {
textView.setText("Hi Heloo");
progressBar.setIndeterminate(false);
progressBar.setMax(100);
progressBar.setProgress(50);
return null;
}
}
}
As a result, your app is always crash with message 结果,您的应用程序总是崩溃并显示消息
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触摸其视图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.