0

我的ProgressDialog適用於我在我的oncreate方法中顯示()的情況。進度對話框膨脹在佈局上onPreExecute()?

public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     pd = ProgressDialog.show(this, "Working", "Retreiving Neaby Restaurants", true, true); // initializes the progress dialog 
     pd.setCanceledOnTouchOutside(false); // on newer versions of android touching outside of the screen will close the dialog. I decided to make it only cancelable when the back button is pressed. 
     setContentView(R.layout.nearby_places_list); 

但是,如果我在異步任務中使用它,因爲它不在create()上,對話框代碼將無法正常工作。該arguements顯示(這一點,「工作」,「Retreiving Neaby餐館」,真正的,真實的)ARNT允許的onCreate()以外:

class MyAsync extends AsyncTask<Void, Integer, Boolean>{ // this task is for populating the listview 

     @Override 
     protected void onPreExecute() { 
      //ProgressDialog.show(context, "Working", "Retreiving Neaby Restaurants"); 
      pd = ProgressDialog.show(this, "Working", "Retreiving Neaby Restaurants", true, true); // initializes the progress dialog 
      pd.setCanceledOnTouchOutside(false); // on newer versions of android touching outside of the screen will close the dialog. I decided to make it only cancelable when the back button is pressed. 
     } 

這有點不安,因爲我想顯示對話框在開始的異步任務,但不久之前調用該任務。

所以我的問題是如何使onPreExecute()異步任務內的工作,我不想顯示(),直到用戶真正開始使用異步任務。

回答

1

使用

pd = ProgressDialog.show(yourActivitName.this, "Working", "Retreiving Neaby Restaurants", true, true); 

onPreExecute()

實際上是活動的Context。將來你需要經常使用一件重要的事情。

你也可以做一個Class level variable上下文activityContext

onCreatesetContentView後初始化像這樣

activityContext=this

,然後你也可以使用

pd = ProgressDialog.show(activityContext, "Working", "Retreiving Neaby Restaurants", true, true);

+1

完美的答案和解釋。不是我習慣在這個網站上看到的東西。謝謝! –