Android的线程修改的EditText线程、Android、EditText

2023-09-06 17:22:45 作者:〃感谢你教我学会冷暖自知

我有在由线程启动另一个函数修改的EditText一个问题:

I am having a problem with modifying EditText in another function started by the thread:

Thread thRead = new Thread( new Runnable(){
    public void run(){
       EditText _txtArea = (EditText) findViewById(R.id.txtArea);
       startReading(_txtArea);
    }
 });

我的功能如下:

my function is as follows:

public void startReading(EditText _txtArea){
         _txtArea.setText("Changed");
}

它总是强制关闭,而试图修改的EditText。是否有人知道为什么吗?

It always force closes while trying to modify the edittext. Does someone know why?

推荐答案

UI意见不应从非UI线程修改。可触摸的UI视图的唯一线索是主或UI线程,一个叫的onCreate()的onStop()和其他类似的组件生命周期的功能。

UI views should not be modified from non-UI thread. The only thread that can touch UI views is the "main" or "UI" thread, the one that calls onCreate(), onStop() and other similar component lifecycle function.

所以,当你的应用程序试图修改非UI线程的用户界面浏览,Android的抛出异常的早期警告你,这是不允许的。这是因为UI不是线程安全的,并且这样的预警实际上是一个很大的特点。

So, whenever your application tries to modify UI Views from non-UI thread, Android throws an early exception to warn you that this is not allowed. That's because UI is not thread-safe, and such an early warning is actually a great feature.

更新:

您可以使用 Activity.runOnUiThread()更新UI。或者使用的AsyncTask 。但是,由于你的情况,你需要不断地从蓝牙读取数据,的AsyncTask 不应该使用。

You can use Activity.runOnUiThread() to update UI. Or use AsyncTask. But since in your case you need to continuously read data from Bluetooth, AsyncTask should not be used.

下面是 runOnUiThread一个例子()

runOnUiThread(new Runnable() {            
    @Override
    public void run() {
        //this will run on UI thread, so its safe to modify UI views.
         _txtArea.setText("Changed");
    }
});