创建独立的“加载”对话
我想创建一个可供任何活动使用的 LoadingDialog
类。我想出了这样的代码:
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();
}
}
但我有一个问题 - 对话框的愚蠢“上下文”!我的“加载”类是独立的,因此我无法调用 getApplicationContext()
,也无法调用 getBaseContext()
。我根本不知道从哪里获取上下文!你有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不创建一个接受 Context 对象的单个参数的构造函数,将其存储在一个字段中,然后您可以在需要的地方访问它?创建类loadingScrn 实例的Activity 只是在创建时传递Context 对象。
请记住将默认构造函数设置为私有,以便只有在提供了 Context 的情况下才可以创建 loadingScrn 的实例。
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.