I have a public class which has some common generic functions, like e.g. for displaying dialogs in my application. I made a generic alertButtonDialog function and want to call it in activities whenever I’m using dialogs. I am very new to Java so please excuse me if it’s very basic.
public static class AlertDialogs{
public static void alertButtonDialog(Activity activity, Context context, String title, String message,
String positiveButton, String negativeButton) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setTitle(title);
alertBuilder.setMessage(message);
alertBuilder.setPositiveButton(positiveButton, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Activity.this.finish(); // *?? How to do this part ??*
// the activity to be finished is the activity which calls this function
}
})
}
}
Later in any other activity, whenever I’m displaying a dialog, I would just do
AlertDialogs.alertButtonDialog(...all my Strings...)
This is only for convenience accessing.
In your
alertButtonDialogfunction, define theActivity activityargument as final. Then, from within theonClicklistener invokeactivity.finish();.Note that you do not need both an
Activityand aContext-since the former extends the later-, unless you are expecting to pass activity as null somewhere.