【问题标题】:Single dialog class for whole project整个项目的单个对话框类
【发布时间】:2018-11-08 12:00:27
【问题描述】:

对话框应该有不同动作的按钮,点击响应应该在调用类中?

我试过了……

 public static void showEmergencyDialog(final Activity activity) {


    final Dialog builder = new Dialog(activity);
    builder.setCanceledOnTouchOutside(false);
    final View dialogView = LayoutInflater.from(activity).inflate(R.layout.emergency_alert_dialog, null);
    final MyTextView emergency_btn =  dialogView.findViewById(R.id.emergency_btn);
    final MyTextView normal_btn =  dialogView.findViewById(R.id.normal_btn);
    final MyTextView sent_btn =  dialogView.findViewById(R.id.sent_btn);
    final MyTextView cancel_btn =  dialogView.findViewById(R.id.cancel_btn);


    emergency_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });


    //Emergency push
    normal_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


        }
    });

    //Sent push
    sent_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

         }
    });

    builder.show();
}

它工作正常,但我无法在调用活动中得到结果

【问题讨论】:

  • 问题太大了。显然,您可以创建一个可以从其他所有类访问的对话框。但是,如果您想触发来自不同类的不同操作,则取决于您的需求模式。

标签: android dialog


【解决方案1】:

试试下面的代码。

public static void showEmergencyDialog(final Activity activity) {
    final Dialog builder = new Dialog(activity);

    final View dialogView = LayoutInflater.from(activity).inflate(R.layout.emergency_alert_dialog, null);

    final MyTextView emergency_btn = (MyTextView) dialogView.findViewById(R.id.emergency_btn);
    final MyTextView normal_btn = (MyTextView) dialogView.findViewById(R.id.normal_btn);
    final MyTextView sent_btn = (MyTextView) dialogView.findViewById(R.id.sent_btn);
    final MyTextView cancel_btn = (MyTextView) dialogView.findViewById(R.id.cancel_btn);
    final EditText emergency_edt = (EditText) dialogView.findViewById(R.id.emergency_edt);

    builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
    builder.setContentView(dialogView);
    builder.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    lp.copyFrom(builder.getWindow().getAttributes());
    lp.width = WindowManager.LayoutParams.MATCH_PARENT;
    lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
    lp.gravity = Gravity.CENTER;
    builder.getWindow().setAttributes(lp);

    cancel_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //dismiss dilog code
            builder.dismiss();
        }
    });

    //Emergency push
    emergency_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

    builder.show();
}

【讨论】:

    【解决方案2】:

    使用Handler.Callback 创建一个Handler 类,如下所示:

    class HandlerMsg implements Handler.Callback
        {
    
            @Override
            public boolean handleMessage(Message msg)
            {
                if(msg.getData().getInt("KEY") == 1)
                {
                   //Here, normal_btn clicked
                }
                else
                {
                   //Here, emergency_btn clicked
                }
    
                return true;
            }
        }
    

    以下是 Dialog

    的听众
    normal_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) 
        {
            Message msg = new Message();
            Bundle b = new Bundle();
            b.putInt("KEY", 1);
            msg.setData(b);
    
            new Handler(new HandlerMsg()).sendMessage(msg);
            builder.dismiss();
        }
    });
    
    emergency_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Message msg = new Message();
            Bundle b = new Bundle();
            b.putInt("KEY", 2);
            msg.setData(b);
    
            new Handler(new HandlerMsg()).sendMessage(msg);
            builder.dismiss();
        }
    });
    

    【讨论】:

      【解决方案3】:

      这是我几个月前编写的对话框处理程序类。虽然我没有在任何地方使用它。它确实遗漏了很多功能,但这对于生成一个没有按钮的AlertDialog 很有用。您创建 DialogHandler 类的对象并传递参数并且它可以工作。只需更改方法onPositiveButton()onNegativeButton() 的代码即可。此外,如果您希望在每个活动中使用相同的对话框,您可以硬编码 constructor 中的值。

      import android.app.Activity;
      import android.app.AlertDialog;
      import android.content.DialogInterface;
      
      public class DialogHandler {
        private Activity activity;
        private String title;
        private String message;
        private Boolean positiveButton;
        private Boolean negativeButton;
        DialogListener dialogListener;
      
        public void createDialogue(Activity activity, String title, String message,
                                 Boolean positiveButton , Boolean negativeButton, DialogListener dialogListener){
          this.activity = activity;
          this.title = title;
          this.message = message;
          this.positiveButton = positiveButton;
          this.negativeButton = negativeButton;
          this.dialogListener = dialogListener;
          generateAlertDialog();
      }
      
      private void generateAlertDialog(){
          AlertDialog.Builder alertDialog = new AlertDialog.Builder(activity)
                  .setIcon(android.R.drawable.ic_dialog_alert)
                  .setTitle(title)
                  .setMessage(message);
                  if(positiveButton){
                      alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                          @Override
                          public void onClick(DialogInterface dialogInterface, int i) {
                              dialogListener.onPositiveButton();
                          }
                      });
                  }
                  if(negativeButton){
                      alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
                          @Override
                          public void onClick(DialogInterface dialogInterface, int i) {
                              dialogListener.onNegativeButton();
                          }
                      });
                  }
                  alertDialog.create();
                  alertDialog.show();
      }
      
      public interface DialogListener{
          void onPositiveButton();
      
          void onNegativeButton();
      }
      

      这是另一个PermissionHandlerClass。两个月前我为我的一个 android 项目写了这篇文章,希望它也会有所帮助。

      【讨论】:

        【解决方案4】:

        在项目中的任意位置创建一个名为 DialogFactory 的新文件,并在文件中实现以下代码

        public class DialogFactory {
        
        public static Dialog createSimpleOkErrorDialog(Context context, String title, String message) {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(context)
                    .setTitle(title)
                    .setMessage(message)
                    .setNeutralButton("OK", null);
            return alertDialog.create();
        }
        
        public static Dialog createSimpleOkErrorDialog(Context context,
                                                       @StringRes int titleResource,
                                                       @StringRes int messageResource) {
        
            return createSimpleOkErrorDialog(context,
                    context.getString(titleResource),
                    context.getString(messageResource));
        }
        
        public static Dialog createSimpleOkErrorDialog(Context context, String message) {
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(context)
                    .setTitle("ERROR")
                    .setMessage(message)
                    .setNeutralButton("OK", null);
            return alertDialog.create();
        }
        
        public static Dialog createSimpleOkErrorDialog(Context context,
                                                       @StringRes int messageResource) {
        
            return createSimpleOkErrorDialog(context, context.getString(messageResource));
        }
        
        public static ProgressDialog createProgressDialog(Context context, String message) {
            ProgressDialog progressDialog = new ProgressDialog(context);
            progressDialog.setTitle("Processing...");
            progressDialog.setMessage(message);
            progressDialog.setCancelable(false);
            return progressDialog;
        }
        
        public static ProgressDialog createProgressDialog(Context context,
                                                          @StringRes int messageResource) {
            return createProgressDialog(context, context.getString(messageResource));
        }
        
        /**
         * Show dialog.
         *
         * @param ctx       the ctx
         * @param msg       the msg
         * @param btn1      the btn1
         * @param btn2      the btn2
         * @param listener1 the listener1
         * @param listener2 the listener2
         * @return the alert dialog
         */
        public static android.app.AlertDialog showDialog(Context ctx, String msg, String btn1,
                                                         String btn2, DialogInterface.OnClickListener listener1,
                                                         DialogInterface.OnClickListener listener2) {
        
            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(ctx);
            builder.setMessage(msg).setCancelable(false)
                    .setPositiveButton(btn1, listener1);
            if (btn2 != null && listener2 != null)
                builder.setNegativeButton(btn2, listener2);
            int LAYOUT_FLAG;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
            } else {
                LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
            }
        
            android.app.AlertDialog alert = builder.create();
            alert.show();
            return alert;
        
        }
        
        /**
         * Show dialog.
         *
         * @param themeRes  the theme ID
         * @param ctx       the ctx
         * @param msg       the msg
         * @param btn1      the btn1
         * @param btn2      the btn2
         * @param listener1 the listener1
         * @param listener2 the listener2
         * @return the alert dialog
         */
        public static android.app.AlertDialog showDialog(int themeRes, Context ctx, String msg, String btn1,
                                                         String btn2, DialogInterface.OnClickListener listener1,
                                                         DialogInterface.OnClickListener listener2) {
        
            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(ctx, themeRes);
            builder.setMessage(msg).setCancelable(false)
                    .setPositiveButton(btn1, listener1);
            if (btn2 != null && listener2 != null)
                builder.setNegativeButton(btn2, listener2);
            int LAYOUT_FLAG;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
            } else {
                LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
            }
        
            android.app.AlertDialog alert = builder.create();
            alert.getWindow().setType(LAYOUT_FLAG);
            alert.show();
            return alert;
        
        }
        
        /**
         * Show dialog.
         *
         * @param ctx       the ctx
         * @param title     the title
         * @param msg       the msg
         * @param btn1      the btn1
         * @param btn2      the btn2
         * @param listener1 the listener1
         * @param listener2 the listener2
         * @return the alert dialog
         */
        public static android.app.AlertDialog showDialog(Context ctx, String title, String msg, String btn1,
                                                         String btn2, DialogInterface.OnClickListener listener1,
                                                         DialogInterface.OnClickListener listener2) {
        
            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(ctx);
            builder.setTitle(title);
            builder.setMessage(msg).setCancelable(false)
                    .setPositiveButton(btn1, listener1);
            if (btn2 != null && listener2 != null)
                builder.setNegativeButton(btn2, listener2);
        
            android.app.AlertDialog alert = builder.create();
            alert.show();
            return alert;
        
        }
        
        /**
         * Show dialog.
         *
         * @param ctx       the ctx
         * @param msg       the msg
         * @param btn1      the btn1
         * @param btn2      the btn2
         * @param listener1 the listener1
         * @param listener2 the listener2
         * @return the alert dialog
         */
        public static android.app.AlertDialog showDialog(Context ctx, int msg, int btn1,
                                                         int btn2, DialogInterface.OnClickListener listener1,
                                                         DialogInterface.OnClickListener listener2) {
        
            return showDialog(ctx, ctx.getString(msg), ctx.getString(btn1),
                    ctx.getString(btn2), listener1, listener2);
        
        }
        
        /**
         * Show dialog.
         *
         * @param ctx      the ctx
         * @param themeRes the theme ID
         * @param msg      the msg
         * @param btn1     the btn1
         * @param btn2     the btn2
         * @param listener the listener
         * @return the alert dialog
         */
        public static android.app.AlertDialog showDialog(Context ctx, int themeRes, String msg, String btn1,
                                                         String btn2, DialogInterface.OnClickListener listener) {
        
            return showDialog(themeRes, ctx, msg, btn1, btn2, listener,
                    (dialog, id) -> dialog.dismiss());
        
        }
        
        /**
         * Show dialog.
         *
         * @param ctx      the ctx
         * @param msg      the msg
         * @param btn1     the btn1
         * @param btn2     the btn2
         * @param listener the listener
         * @return the alert dialog
         */
        public static android.app.AlertDialog showDialog(Context ctx, String msg, String btn1,
                                                         String btn2, DialogInterface.OnClickListener listener) {
        
            return showDialog(ctx, msg, btn1, btn2, listener,
                    (dialog, id) -> dialog.dismiss());
        
        }
        
        /**
         * Show dialog.
         *
         * @param ctx      the ctx
         * @param msg      the msg
         * @param btn1     the btn1
         * @param btn2     the btn2
         * @param listener the listener
         * @return the alert dialog
         */
        public static android.app.AlertDialog showDialog(Context ctx, int msg, int btn1,
                                                         int btn2, DialogInterface.OnClickListener listener) {
        
        
            return showDialog(ctx, ctx.getString(msg), ctx.getString(btn1),
                    ctx.getString(btn2), listener);
        
        }
        
        /**
         * Show dialog.
         *
         * @param ctx      the ctx
         * @param msg      the msg
         * @param listener the listener
         * @return the alert dialog
         */
        public static android.app.AlertDialog showDialog(Context ctx, String msg,
                                                         DialogInterface.OnClickListener listener) {
        
            return showDialog(ctx, msg, ctx.getString(android.R.string.ok), null,
                    listener, null);
        }
        
        /**
         * Show dialog.
         *
         * @param ctx      the ctx
         * @param msg      the msg
         * @param listener the listener
         * @return the alert dialog
         */
        public static android.app.AlertDialog showDialog(Context ctx, int msg,
                                                         DialogInterface.OnClickListener listener) {
        
            return showDialog(ctx, ctx.getString(msg),
                    ctx.getString(android.R.string.ok), null, listener, null);
        }
        
        /**
         * Show dialog.
         *
         * @param ctx the ctx
         * @param msg the msg
         * @return the alert dialog
         */
        public static android.app.AlertDialog showDialog(Context ctx, String msg) {
        
            return showDialog(ctx, msg, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
        
                    dialog.dismiss();
                }
            });
        
        }
        
        /**
         * Show dialog.
         *
         * @param ctx the ctx
         * @param msg the msg
         * @return the alert dialog
         */
        public static android.app.AlertDialog showDialog(Context ctx, int msg) {
        
            return showDialog(ctx, ctx.getString(msg));
        
        }
        
        /**
         * Show dialog.
         *
         * @param ctx      the ctx
         * @param title    the title
         * @param msg      the msg
         * @param listener the listener
         */
        public static void showDialog(Context ctx, int title, int msg,
                                      DialogInterface.OnClickListener listener) {
        
            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(ctx);
            builder.setMessage(msg).setCancelable(false)
                    .setPositiveButton(android.R.string.ok, listener);
            builder.setTitle(title);
            android.app.AlertDialog alert = builder.create();
            alert.show();
        }
        
        public static void showEditTextDialog(Context ctx, String title, String hint,
                                              DialogInterface.OnClickListener listener) {
            AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
            builder.setTitle(title);
        
            final EditText input = new EditText(ctx);
            input.setHint(hint);
            input.setSingleLine(true);
            input.setLines(5);
            input.setMaxLines(5);
            input.setGravity(Gravity.LEFT | Gravity.TOP);
            builder.setView(input);
            builder.setPositiveButton(android.R.string.ok, listener);
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            AlertDialog alert = builder.create();
            alert.show();
        }
        
        public static void showDialog(Context ctx, String title, String msg,
                                      DialogInterface.OnClickListener listener) {
        
            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(ctx);
            builder.setMessage(msg).setCancelable(false)
                    .setPositiveButton(android.R.string.ok, listener);
            builder.setTitle(title);
            android.app.AlertDialog alert = builder.create();
            alert.show();
        }
        
        /**
         * Hide keyboard.
         *
         * @param ctx the ctx
         */
        public static final void hideKeyboard(Activity ctx) {
        
            if (ctx.getCurrentFocus() != null) {
                InputMethodManager imm = (InputMethodManager) ctx
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(ctx.getCurrentFocus().getWindowToken(),
                        0);
            }
        }
        
        /**
         * Hide keyboard.
         *
         * @param ctx the ctx
         * @param v   the v
         */
        public static final void hideKeyboard(Activity ctx, View v) {
        
            try {
                InputMethodManager imm = (InputMethodManager) ctx
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        public static void showExitDialog(Activity activity) {
            final boolean[] check = new boolean[1];
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setPositiveButton("Yes", (dialog, which) -> {
                        activity.finish();
                        if (check[0]) {
                            TinyDB.getInstance(activity).putBoolean("dialog_status", true);
                        } else {
                            TinyDB.getInstance(activity).putBoolean("dialog_status", false);
                        }
                    }
            ).setNegativeButton("No", (dialog, which) -> {
        
            });
            AlertDialog dialog = builder.create();
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        
            dialog.show();
        
            Button b = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
            b.setTextColor(ContextCompat.getColor(activity, R.color.colorAccent));
            b = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
            b.setTextColor(ContextCompat.getColor(activity, R.color.colorAccent));
        
        }
        

        }

        现在,在您想要提示对话框的任何操作上,只需调用带有消息和所需按钮名称的方法即可

        DialogFactory.showDialog(MainActivity.this, "Do you want to exit", "Yes", "Cancel", (dialog, which) -> finish());
        

        记住在对话框工厂类中你必须导入所有相关的类名。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-12-11
          • 1970-01-01
          • 2012-11-22
          • 1970-01-01
          相关资源
          最近更新 更多