如何重用android alertdialog [英] how to reuse android alertdialog

查看:145
本文介绍了如何重用android alertdialog的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重用alertDialog的代码,并将其放在另一个java文件中,作为函数调用.但是"this"不能用来代替"MyActivity.this"吗?如何将其作为参数传递?如果代码是通用的,则最好.

I want to reuse the code for alertDialog and put it in another java file as function call . But "this" cannot be used to replace the "MyActivity.this"? How to pass it as a parameter? Best if the code is generic.

    AlertDialog alertDialog = new AlertDialog.Builder(MyActivity.this).create();
            alertDialog.setTitle("Alert");
            alertDialog.setMessage("Alert message to be shown");
            alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
            alertDialog.show();

推荐答案

您可以在单独的类中使用类似的内容,例如我使用过AlertUtils.java:

You can use something like this in a separate class, for example I have used AlertUtils.java:

public class AlertUtils
{
    public static void showOKDialog(Context context, String title, String message)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setPositiveButton(android.R.string.ok, null);
        builder.show();
    }
}

在此方法中,您通过的Context可能是Activity的this,例如:MyActivity.this或片段的getContext()

In this method, the Context you pass through could be your Activity's this, eg: MyActivity.this or a fragment's getContext()

AlertUtils.showOKDialog(MyActivity.this, "title of dialog", "message to display in dialog");

这篇关于如何重用android alertdialog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆