我有问题。 MainActivity和类下面有代码:Testing。如何在执行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();
}
}
答案 0 :(得分:0)
在ProgressDialog
中创建AsyncTask
,然后将其从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);