如何在 UI 线程之外执行 UI 操作?

How is it possible to do UI operations outside the UI thread?

我尝试在 UI 线程之外的普通线程中设置文本,但效果很好。

    private TextView mTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView) findViewById(R.id.my_text);
        Log.d("**** ONCREATE****", Thread.currentThread().getId()+"");
        new BackgroundTestThread().start();
    }

    class BackgroundTestThread extends Thread{
    @Override
    public void run() {
         Log.d("**** THREAD****", Thread.currentThread().getId()+"");
         mTextView.setText("Text was set successfully", TextView.BufferType.EDITABLE);
         }
    }

看到这种情况发生,我感到非常惊讶。我认为工作线程永远无法更新主线程,因为只有主线程可以呈现 UI 元素(TextView、EditText 等),如果我们尝试更新,肯定会出现异常。

为什么会这样?

它有时不会工作,因为它不是线程安全的。所以推荐使用handler或者runonuithead。

另一种在主 UI 线程之外执行 UI 操作安全的方法。

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
           mTextView.setText("Text was set successfully", TextView.BufferType.EDITABLE);
        }
    });

Android 不会到处检查它的 UI 线程是否如此在某些情况下它可能工作。但它从不线程 safe.The 首选方式是显示在 UI线程。