如何创建A"你想继续吗?"警报框

时间:2014-12-24 20:56:36

标签: java android

在我的应用程序中,我有一个按钮,当按下时,我希望它显示一个警告对话框,询问您是否要继续。它将有两个按钮:a"继续"并且"不要继续"。我将打开对话框的方法打开新的Activity,如下所示:

case R.id.bRegister:
          try{
              //the method for opening the alert box goes somewhere here but i don't know where yet.
              Class ourClass = Class.forName("org.health.blablablabla.app.RegisterData");
              Intent ourIntent = new Intent(MainActivity.this,ourClass);
              finish();

              startActivity(ourIntent);
              overridePendingTransition(R.animator.fadein,R.animator.fadeout);

          } catch (ClassNotFoundException e) {
              e.printStackTrace();
          }

这是我目前用于警报对话框方法的内容:

 private void showWarning(){
    AlertDialog.Builder warning = new AlertDialog.Builder(this);
    warning.setTitle("Existing Data");
    warning.setMessage("There is already existing data. If you continue all previous data will be deleted. Are you sure you want to continue?");
    warning.setPositiveButton("Continue",new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface arg0, int arg1)
        {
            arg0.dismiss();
        }
    });
    warning.setNegativeButton("Do Not Continue",new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // do nothing
        }
    });
}

我的问题是将该方法放在第一个代码块中的位置,以及如何将其设置为“当不继续"按下按钮,New Activity" RegisterData"没有开放。

1 个答案:

答案 0 :(得分:1)

您可以制作YesNoSampleActivity并使用AlertDialog.Builder,如下所示:

public class YesNoSampleActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //Put up the Yes/No message box
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder
    .setTitle("Erase hard drive")
    .setMessage("Are you sure?")
    .setIcon(android.R.drawable.ic_dialog_alert)
    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {                    
            //Yes button clicked, do something
            Toast.makeText(YesNoSampleActivity.this, "Yes button pressed", 
                           Toast.LENGTH_SHORT).show();
        }
    })
    .setNegativeButton("No", null)                      //Do nothing on no
    .show();


    // Continue code after the Yes/No dialog
    // ....
  }
}