AsyncTask Android 关闭 ProgressDialog
Posted
技术标签:
【中文标题】AsyncTask Android 关闭 ProgressDialog【英文标题】:AsynTask Android Close ProgreesDialog 【发布时间】:2015-05-12 03:03:36 【问题描述】:我有问题。下面有 MainActivity 和类的代码:测试。执行 asyntask 方法 onPostExecute 后如何关闭 ProgressDialog?它在单独的班级中。有什么想法吗?
public class MainActivity extends ActionBarActivity
private SwitchCompat tg;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tg = (SwitchCompat) findViewById(R.id.switch1);
tg.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked)
if (isChecked)
Toast.makeText(getApplicationContext(), "START", Toast.LENGTH_SHORT).show();
pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Loading...");
pd.setMessage("Please wait.");
pd.show();
Testing testing= new Testing(getApplicationContext());
xml.execute();
else
Toast.makeText(getApplicationContext(), "Synchronisation is offline.", Toast.LENGTH_SHORT).show();
if (pd != null)
pd.dismiss();
);
还有我的 asynctask 类:
public class Testing extends AsyncTask<Void, Void, Void>
Boolean dataFromAsyncTask;
private Context context;
ProgressDialog pd;
public Testing (Context context)
this.context = context;
@Override
protected void onPreExecute()
super.onPreExecute();
Toast.makeText(context, "PRE EXECUTE.", Toast.LENGTH_SHORT).show();
@Override
protected Void doInBackground(Void... arg0)
return null;
@Override
protected void onPostExecute(Void result)
super.onPostExecute(result);
Toast.makeText(context, "POST EXECUTE.", Toast.LENGTH_SHORT).show();
【问题讨论】:
【参考方案1】:在您的AsyncTask
中创建ProgressDialog
并将其从Activity
中删除。
@Override
protected void onPreExecute()
super.onPreExecute();
Toast.makeText(context, "PRE EXECUTE.", Toast.LENGTH_SHORT).show();
pd = new ProgressDialog(this.context);
然后您可以在onPostExecute()
中将其关闭
@Override
protected void onPostExecute(Void result)
super.onPostExecute(result);
Toast.makeText(context, "POST EXECUTE.", Toast.LENGTH_SHORT).show();
if (pd != null && pd.isShowing())
pd.dismiss();
但我会通过 Activity Context
而不是 Application Context
。
Testing testing= new Testing(MainActivity.this);
【讨论】:
更改我的代码时出现问题:无法添加窗口 -- 令牌 null 不适用于应用程序 查看我的编辑。你没有像我建议的那样更改Context
。以上是关于AsyncTask Android 关闭 ProgressDialog的主要内容,如果未能解决你的问题,请参考以下文章
AsyncTask Android 关闭 ProgressDialog