在另一个线程中访问UI视图不会*导致崩溃.为什么? [英] Accessing UI view in another thread does *not* cause a crash. Why?

查看:104
本文介绍了在另一个线程中访问UI视图不会*导致崩溃.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部:

我真的还不抱怨处理程序.我认为下面的代码经过修改-以便直接使用UI小部件(进度条)而不是使用处理程序,而是会导致跨线程异常.但事实并非如此.所以,我的问题是,这段代码是否应该崩溃?如果没有,那么我什么时候需要使用处理程序?

I really don't grok handlers yet. I thought that the code below -- modified so that, instead of using a handler, the UI widget (progress bar) was accessed directly -- would cause a cross-threading exception. But it doesn't. So, my question is, shouldn't this code crash? And if it doesn't, then when do I need to use a handler?

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        progress = 0;
        progressBar = (ProgressBar) findViewById(R.id.progressbar);
        progressBar.setMax(200);

        //---do some work in background thread---
        new Thread(new Runnable()
        {
            public void run()
            {
                //ó-do some work hereó-
                while (progressStatus < 200)
                {
                    progressStatus = doSomeWork();
                    progressBar.setProgress(progressStatus); // not on UI thread
                    //ó-Update the progress baró-            // so shouldn't it crash?
//                    handler.post(new Runnable()
//                    {
//                        public void run() {
//                            progressBar.setProgress(progressStatus);
//                        }
//                    });
                }

                //---hides the progress bar---
                handler.post(new Runnable()
                {
                    public void run()
                    {
                        //---0 - VISIBLE; 4 - INVISIBLE; 8 - GONE---
                        progressBar.setVisibility(View.GONE);
                    }
                });
            }

推荐答案

现在,ProgressBar具有允许在后台线程上调用setProgress()的逻辑.它检查您所处的线程,并在需要时对Runnable做自己的post().您可以在源代码中看到.

Nowadays, ProgressBar has logic that allows setProgress() to be called on a background thread. It checks to see what thread you are on and does its own post() of a Runnable if needed. You can see this in the source code.

这篇关于在另一个线程中访问UI视图不会*导致崩溃.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆