我正在从另一个活动(Activity1)开始一个活动(Activity2)。我正在Activity1的公共方法中显示进度对话框。当我从Activity2调用此方法时,会发生异常。
public class Activity1 extends Activity{
private ProgressDialog progressDialog;
public Activity1(){
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_activity1);
}
public void showDialog(){
progressDialog = ProgressDialog.show(Activity1.this,
"Please Wait");
progressDialog.setProgressStyle(R.style.DialogStyle);
progressDialog.setCancelable(true);
progressDialog.setCanceledOnTouchOutside(true);
}
//On Clicking a button this method gets called
private void nextActivity(){
Intent intent = new Intent(Activity1.this, Activity2.class);
startActivity(intent);
}
public class Activity2 extends Activity{
private Activity1 activity1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_activity2);
activity1 = new Activity1();
activity1.showDialog();
}
}
从Activity2调用Activity1< showDialog()方法后,它在showDialog()方法的以下行中给出了异常:
progressDialog = ProgressDialog.show(Activity1.this, "请等待");
我也尝试将ProgressDialog的对象设为静态但不起作用
答案 0 :(得分:1)
这是在另一个Activity
中访问该方法的错误方法。
最好的方法是添加Base Activity
并在那里移动showDialog代码。您可以在Activity
Base Activity
代码
像这样创建基本活动
public class BaseActivity extends Activity {
private ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
progressDialog = ProgressDialog.show(Activity1.this,
"Please Wait");
}
public void showDialog(){
progressDialog.setProgressStyle(R.style.DialogStyle);
progressDialog.setCancelable(true);
progressDialog.setCanceledOnTouchOutside(true);
progressDialog.show();
}
现在,您可以从所有必需的活动中扩展BaseActivity,并在需要时调用showDialog()方法。
public Activity2 extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_activity2);
// show the progress dialog
showDialog();
}
}