標籤:only the original th 在非ui線程中更新ui android在新線程中更新ui 在timer中更新ui
當在非UI線程中更新UI(程式介面)時會出現如所示的異常:
那如何才能在非UI線程中更細UI呢?
方法有很多種,在這裡主要介紹兩種:
第一種:在需要更新UI的程式碼後加Looper.prepare();與Looper.loop();兩句話即可。如:
new Thread(){@Overridepublic void run() {// TODO Auto-generated method stubtxtRotation.setText("在非UI線程中更新UI!");Looper.prepare();Looper.loop();}}.start();
第二種:使用如下方法:
new Thread(){@Overridepublic void run() {// TODO Auto-generated method stubshowToastByRunnable(MainActivity.this, "", 3000);}}.start();
/** * 在非UI線程中使用Toast * @param context 上下文 * @param text 用以顯示的訊息內容 * @param duration 訊息顯示的時間 * */private void showToastByRunnable(final Context context, final CharSequence text, final int duration) { Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run() { Toast.makeText(context, text, duration).show(); } });}
Android開之在非UI線程中更新UI