进度对话框在布局onPreExecute()上面膨胀?

时间:2012-11-27 18:25:40

标签: android android-asynctask android-activity progressdialog android-progressbar

我的ProgressDialog适用于我在oncreate方法中显示()的情况。

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);

但是,如果我在异步任务中使用它,对话框代码将无法工作,因为它不在on create()中。争论表明(这个,“工作”,“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()上的异步任务中使其工作我不希望show()直到用户实际开始使用异步任务。

1 个答案:

答案 0 :(得分:1)

使用

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

中的

实际上是活动的Context。您将来需要经常使用的重要事项。

您还可以制作Class level variable 上下文活动上下文

并在setContentView onCreate之后将其初始化为

activityContext=this

然后你也可以使用

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