Wednesday, January 9, 2013

[Android] 使用AsyncTask更新UI介面

AsyncTask的子類別
抽象函式
doInBackground(Params...params)
此函式實作背景執行緒中所要進行的工作
完成之後 會呼叫以下函式
onPostExecute(Result result)


package com.example.asynctasktest;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class AsyncTaskTest extends Activity {
 TextView m_textView;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_async_task_test);
  m_textView = (TextView) findViewById(R.id.main_text);
  new TextViewChanger().execute();
 }

//變更文字區塊文字內容
 private void changeViewText(){
  m_textView.setText(R.string.screen2);
 }

//實作一個TextViewChanger的類別繼承AsyncTask,且可以在背景執行一些工作,執行完之後會
//做onPostExecute

 private class TextViewChanger extends AsyncTask{
  @Override
  protected Void doInBackground(Void... arg0) {
   // TODO Auto-generated method stub
   try{
    Thread.sleep(10000);
   }catch(InterruptedException e){
    e.printStackTrace();
   }
   return null;
  }

//背景做完之後執行的函數
  protected void onPostExecute(Void noUse){
   changeViewText();
  }

 }
 @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_async_task_test, menu);
  return true;
 }
}

No comments:

Post a Comment