我正在使用Handler在進行搜索時使UI響應。我使用了Handler,但爲什麼它仍然顯示錯誤「只有創建視圖層次結構的原始線程才能觸及其視圖」。長時間使用Handler方法
@Override
public void onClick(final View view) {
if (view.getId() == R.id.searchButton) {
processThread(searchEditText.getText().toString());
}
}
private void processThread(final String word) {
progressDialog.show();
new Thread() {
@Override
public void run() {
// This is a long time method.
searchWord(word);
searchHandler.sendEmptyMessage(0);
};
}.start();
}
private void searchWord(final String word) {
final String result = dictionaryClient.lookup(word);
resultTextView.setText(result);
}
private final Handler searchHandler = new Handler() {
@Override
public void handleMessage(final Message msg) {
super.handleMessage(msg);
progressDialog.dismiss();
};
};
07-04 22:04:54.699: ERROR/AndroidRuntime(8815): android.view.ViewRoot$CalledFromWrongThreadException:
Only the original thread that created a view hierarchy can touch its views.
07-04 22:04:54.699: ERROR/AndroidRuntime(8815): at android.view.ViewRoot.checkThread(ViewRoot.java:2802)
07-04 22:04:54.699: ERROR/AndroidRuntime(8815): at android.view.ViewRoot.requestLayout(ViewRoot.java:594)
07-04 22:04:54.699: ERROR/AndroidRuntime(8815): at android.view.View.requestLayout(View.java:8125)
07-04 22:04:54.699: ERROR/AndroidRuntime(8815): at android.view.View.requestLayout(View.java:8125)
07-04 22:04:54.699: ERROR/AndroidRuntime(8815): at android.view.View.requestLayout(View.java:8125)
07-04 22:04:54.699: ERROR/AndroidRuntime(8815): at android.view.View.requestLayout(View.java:8125)
07-04 22:04:54.699: ERROR/AndroidRuntime(8815): at android.view.View.requestLayout(View.java:8125)
07-04 22:04:54.699: ERROR/AndroidRuntime(8815): at android.widget.ScrollView.requestLayout(ScrollView.java:1200)
07-04 22:04:54.699: ERROR/AndroidRuntime(8815): at android.view.View.requestLayout(View.java:8125)
07-04 22:04:54.699: ERROR/AndroidRuntime(8815): at android.widget.TextView.checkForRelayout(TextView.java:5371)
07-04 22:04:54.699: ERROR/AndroidRuntime(8815): at android.widget.TextView.setText(TextView.java:2688)
07-04 22:04:54.699: ERROR/AndroidRuntime(8815): at android.widget.TextView.setText(TextView.java:2556)
07-04 22:04:54.699: ERROR/AndroidRuntime(8815): at android.widget.TextView.setText(TextView.java:2531)
07-04 22:04:54.699: ERROR/AndroidRuntime(8815): at com.megadict.activity.DictionaryActivity.searchWord(DictionaryActivity.java:135)
07-04 22:04:54.699: ERROR/AndroidRuntime(8815): at com.megadict.activity.DictionaryActivity.access$1(DictionaryActivity.java:133)
07-04 22:04:54.699: ERROR/AndroidRuntime(8815): at com.megadict.activity.DictionaryActivity$2.run(DictionaryActivity.java:146)
編輯:我跟着this article。
這個答案不是最好的,但它適用於我的問題!我決定改用AsyncTask。 – Emerald214