如何在Android应用程序中使用AlertDialog的公共类

时间:2015-09-29 06:54:38

标签: android alertdialog android-alertdialog

我想在我的Android应用程序的每个屏幕中使用AlertDialog,所以我想创建一个公共类" Activity_AlertDialog"在我的项目中将包含AlertDialog的代码。无论我在项目中需要一个对话框,我都会打电话给这个班级。 但是,如何从这个普通班级中调用正面和负面按钮? 我的示例代码:

package com.example.AlertDialog;



public class Activity_AlertDialog extends android.app.AlertDialog {

Context context;
String title, msg, negBtn, posBtn;

public Activity_AlertDialog(final Context context, String title, String   
message,
        String negBtn, String posBtn) {
    super(context);
    this.context = context;
    this.msg = message;
    this.title = title;
    this.negBtn = negBtn;
    this.posBtn = posBtn;

    Activity_AlertDialog.Builder alertDialog = new     
Activity_AlertDialog.Builder(context);

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

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

    // Setting Icon to Dialog
    alertDialog.setIcon(R.drawable.ttt_logo);

    // Setting OK Button
    alertDialog.setPositiveButton(posBtn,
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // Write your code here to execute after dialog closed
                    Toast.makeText(context, "You clicked on OK",
                            Toast.LENGTH_SHORT).show();
                }
            });
    alertDialog.setNegativeButton(negBtn,
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Toast.makeText(context, "You clicked on No",
                            Toast.LENGTH_SHORT).show();


                }
            });

}
}

Function in my Application where I'm calling this class:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {


        case Utility.MENU_LOGOUT:
            Activity_AlertDialog dialog = new 
Activity_AlertDialog(Activity_Search.this, "Alert Dialog",
                    "You have an unsaved Draft.\n"+"Do you want to save 
it?","No","Yes");
            // How to call positive and negative buttons from Activity_AlertDialog class here?????

            return true;


        default:
            return ;
        }
    }

1 个答案:

答案 0 :(得分:0)

你可以使用

  

dialog.getButton(AlertDialog.BUTTON_POSITIVE).performClick();

调用对话框的正面按钮,并使用AlertDialog.BUTTON_NEGATIVE触发对话框的否定按钮。