我是android的新手,我尝试为警报对话框编写类MyAlertDialog以在需要警报对话框的所有地方使用它。我在类中写了一个方法showAlertDialog来做到这一点。我发现该方法必须是静态的。谁能告诉我为什么它应该是静态的?这是我的代码:

public class MyAlertDialog extends AppCompatActivity {

public static void alertDialogShow(Context context, String message) {

    final Dialog dialog;
    TextView txtAlertMsg;
    TextView txtAlertOk;

    dialog = new Dialog(context);
    dialog.setContentView(R.layout.activity_my_alert_dialog);
    txtAlertOk = (TextView) dialog.findViewById(R.id.txtAalertOk);
    txtAlertMsg = (TextView) dialog.findViewById(R.id.txtAlertMsg);
    txtAlertMsg.setText(message);
    txtAlertOk.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
    dialog.show();
}


}

我叫它像下面这样:

MyAlertDialog.alertDialogShow(MainActivity.this,"Here is my message");

最佳答案

不必是静态的

您也可以通过非静态方式执行此操作:

public class MyAlertDialog {

private Context context;
private String message;

public MyAlertDialog(Context context,String message){
    this.context = context;
    this.message = message;
}

public void alertDialogShow() {

    final Dialog dialog;
    TextView txtAlertMsg;
    TextView txtAlertOk;

    dialog = new Dialog(context);
    dialog.setContentView(R.layout.activity_my_alert_dialog);
    txtAlertOk = (TextView) dialog.findViewById(R.id.txtAalertOk);
    txtAlertMsg = (TextView) dialog.findViewById(R.id.txtAlertMsg);
    txtAlertMsg.setText(message);
    txtAlertOk.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
    dialog.show();
}


调用它:

MyAlertDialog myAlertDialog = new MyAlertDialog(MainActivity.this,"Here is my message");

myAlertDialog.alertDialogShow();

10-04 18:50