开发者

How to call generic activity finish

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 t开发者_StackOverflow中文版o 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 alertButtonDialog function, define the Activity activity argument as final. Then, from within the onClick listener invoke activity.finish();.

public static void alertButtonDialog(final Activity activity, Context context, String title, String message, 
        String positiveButton, String negativeButton) {

    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
    ...
    alertBuilder.setPositiveButton(positiveButton, new OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            activity.finish();
        }
    })

}

Note that you do not need both an Activity and a Context -since the former extends the later-, unless you are expecting to pass activity as null somewhere.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜