无错误非UI线程调用textView.setText。为什么?线程、错误、setText、UI

2023-09-07 12:46:35 作者:人定规矩钱定人.?

我写了下面code基本上开始从一个TextView的文本更改线程。

我在等一个错误,因为我从另一个线程比主线程访问TextTiew(UI元素)。

但它工作正常。认为这应该是不可能的,据我所知。 我不明白这一点,我缺少什么?

 公共类MainActivity延伸活动{
    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);

        TextView的电视=(TextView中)findViewById(R.id.view1);
        tv.setText(Thread.currentThread()的getName());

        螺纹theThread =新主题(新aRunnable(电视));
        theThread.start();
    }
    @覆盖
    公共布尔onCreateOptionsMenu(功能菜单){
        //充气菜单;这增加了项目操作栏,如果它是present。
        。getMenuInflater()膨胀(R.menu.activity_main,菜单);
        返回true;
    }
}
 

 公共类ARunnable实现Runnable {
    TextView的电视;
    公共ARunnable(TextView的电视){
        this.tv =电视;
    }
    @覆盖
    公共无效的run(){
        tv.setText(tv.getText()+ - + Thread.currentThread()的getName());
    }

}
 

解决方案

的的文档说不要从UI线程以外访问Android UI工具包。他们不说,安卓本身含有任何code至$ P $这样做pvent你。这仅仅是一个糟糕的主意,可能产生意想不到的副作用。

Android 子线程 UI 操作真的不可以

您应该叫 Activity.runOnUiThread()更新从其他线程的用户界面。

I wrote the following Code which basically starts a Thread from which the text of a TextView is changed.

I was expecting an error because I access a TextTiew (UI-element) from another Thread than the main-Thread.

But it works fine. Thought this shouldn't be possible as far as I know. I don't get it, what am I missing?

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView tv = (TextView) findViewById(R.id.view1);
        tv.setText(Thread.currentThread().getName());

        Thread theThread = new Thread(new aRunnable(tv));
        theThread.start();      
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

public class ARunnable implements Runnable{     
    TextView tv;    
    public ARunnable(TextView tv){
        this.tv = tv;
    }   
    @Override
    public void run() {
        tv.setText(tv.getText()+"----" + Thread.currentThread().getName()); 
    }

}

解决方案

The docs say Do not access the Android UI toolkit from outside the UI thread. They do not say that Android itself contains any code to prevent you from doing so. It is merely a Bad Idea that could have unintended side effects.

You should call Activity.runOnUiThread() to update the UI from other threads.