問題描述
我在線程啟動的另一個函數中修改 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);
}
});
我的功能如下:
public void startReading(EditText _txtArea){
_txtArea.setText("Changed");
}
它總是在嘗試修改編輯文本時強制關閉.有人知道為什么嗎?
It always force closes while trying to modify the edittext. Does someone know why?
推薦答案
不應從非 UI 線程修改 UI 視圖.唯一可以接觸 UI 視圖的線程是main"或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 線程修改 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");
}
});
這篇關于Android Thread 修改 EditText的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!