Creating independent "Loading" dialog
I would like to create a LoadingDialog
class that could be used by ANY activity. I came up with code like this:
public class loadingScrn extends AsyncTask<String,Void,Void> {
ProgressDialog dialog=null;
protected void onPreExecute() {
dialog = ProgressDialog.show(null, "", "", true);
}
protected Void doInBackground(String... text) {
dialog.setMessage(text[0]);
return(null);
}
protected void onProgressUpdate() { }
protected void onPostExecute(Void unused) {
if(dialog!=null)
dialog.dismiss();
}
开发者_如何转开发
}
But I have a problem - stupid "context" of dialog! My "loading" class is independent so I can't call getApplicationContext()
, nor getBaseContext()
. I simply have no idea where to get context from! Do you have any idea?
Why not create a constructor which takes a single argument of a Context object, store this in a field, and then you can access it wherever it is needed? The Activity creating an instance of class loadingScrn simply passes the Context object as it is created.
Remember to make the default constructor private so that it is only possible to create an instance of loadingScrn if a Context is provided.
public class loadingScrn extends AsyncTask<String,Void,Void> {
private final Context context;
public loadingScrn( Context context )
{
super();
this.context = context;
}
private locaingScrn()
{
super();
}
.
.
.
}
精彩评论