2011-06-21 82 views
0

我有一個程序,每次單擊按鈕時都會使用異步任務...我不想每次單擊它時都要輸入整個AsyncTask ..這將是單調乏味的。有什麼更好的辦法可以做到這一點? 這是一些源代碼。AsyncTask實例

new AsyncTask<Void, Integer, Void>(){ 

      @Override 
     protected Void doInBackground(Void... arg0) { 
      try {     
      Thread.sleep(1000);    
      } catch (InterruptedException e) {       
       e.printStackTrace();    
        }    
        return null; 
      } 
      @Override   
     protected void onPostExecute(Void result) {    
        text1.setText("Nice to meet you "+name); 
        dismissDialog(typeBar); 
        } 


       @Override   
     protected void onPreExecute() { 
      typeBar = 0; 
     showDialog(typeBar); 

     } 

     }.execute((Void)null); 

     } 
    }); 
    } 

回答

3

創建一個擴展的AsyncTask一個新的類:

public class MyTask extends AsyncTask<Void, Integer, Void> 
{ 
    @Override 
    protected Void doInBackground(Void... arg0) 
    { 
    } 
} 

然後徘徊無論你需要它只是這樣做:

new MyTask.execute(); 

完蛋了!玩的開心!

+0

好的,謝謝,這聽起來像什麼即時通訊尋找。我要去實現它。但還有一個問題。我希望我的文本在AsyncTask類中不斷變化...我是否需要在Async類中每次創建一個方法來更改textView?這將是非常乏味的。 – theITRanger22

+0

@ theITRanger22你能解釋一下爲什麼你想修改文本嗎? – olamotte

+0

@olamotee好吧所以本程序首先使用asynTask來顯示進度對話框...然後是一個textView ...用戶然後輸入一些信息,然後單擊按鈕和textViewchanges ....這在整個程序中都會發生。我只是想找到一個更簡單的方法來實現這一點。 – theITRanger22

0

把它放在公共或私人課堂。然後您可以根據新創建的類的名稱來引用/實例化它。