2011-06-21 53 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

把它放在公共或私人课堂。然后您可以根据新创建的类的名称来引用/实例化它。