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

时间:2017-12-07 07:29:20

标签: java android multithreading view android-handler

我试图在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等),如果我们尝试更新,我们肯定会得到一个例外。

为什么会这样?

3 个答案:

答案 0 :(得分:3)

它有时不起作用,因为它不是线程安全的。因此,建议使用handler或runonuithead。

答案 1 :(得分:1)

Android并不会检查其UI线程是否存在或在某些情况下它可能无效。但它从不线程安全。首选方法是在UIThread中显示。

答案 2 :(得分:0)

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

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