简体   繁体   中英

Go back to MainActivity when OK pressed in AlertDialog in Android

I am using this alert dialog to pop-up a message saying that no Active internet connection is available.

I want to get back to the MainActivity when the user click's OK but i can't seem to get this going.

package com.xx.xx.xxhelper;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;


public class AlertDialogManager {

public void showAlertDialog(Context context, String title, String message,
        Boolean status) {
    AlertDialog alertDialog = new AlertDialog.Builder(context).create();

    // Setting Dialog Title
    alertDialog.setTitle(title);

    // Setting Dialog Message
    alertDialog.setMessage(message);

    if(status != null)
        // Setting alert dialog icon
        alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

    // Setting OK Button
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
    }

    });

    // Showing Alert Message
    alertDialog.show();
}
}

I added

public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(AlertDialogManager.this, HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)    
startActivity(intent);
}
});

But i get:

  1. The constructor Intent(AlertDialogManager, Class) is undefined
  2. The method startActivity(Intent) is undefined for the type new DialogInterface.OnClickListener(){}

any clues?

Pass in the Activity context (to start activity when OK is clicked on the alert dialog) using something like the following:

public void onClick(DialogInterface dialog, int which) {
    Intent intent = new Intent(context, HomeActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
}

You should use the context passed:

 public void onClick(DialogInterface dialog, int which) {
      Intent intent = new Intent(context, HomeActivity.class);
      intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);    
      context.startActivity(intent);
    }
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM