Why strange naming convention of “AlertDialog.Builder” instead of “AlertDialogBuilder” in Android

前端 未结 4 1225
时光取名叫无心
时光取名叫无心 2021-02-08 06:13

Why not

AlertDialogBuilder builder = new  AlertDialogBuilder(this);
builder.setTitle(\"foo\");

instead of

AlertDialog.Builder          


        
4条回答
  •  悲哀的现实
    2021-02-08 06:36

    The approach used to construct AlertDialog Object is called Builder Pattern to enhance readability. When you want to construct a new object but this object requires a lot of properties to create it like too many parameters (more than 4) passing to constructor you will got confused . If you want to know more about builder pattern I think this answer will satisfy your needs. AlertDialog construction is quite similar to the example in the link :

    @Override 
    public Dialog onCreateDialog(Bundle savedInstanceState) {
    return new AlertDialog.Builder(getActivity())
               .setMessage("Do you really want to exit?")
               .setCancelable(false)
               .setNegativeButton("No", 
                        new DaialogInterface.onClickListener() {
                                public void onClick(DialogInterface dialog, 
                                int id) {
                                        ((AlertDialogActivity) getActivity())
                                                    .continueShutdown(false);
                                    }
    
                            })
               .setPositibeButton("Yes", 
                        new DialogInterface.onClickListener()) {
                            public void onClick(
                                    final DialogInterface dialog, int id) {
                                        ((AlertDialogActivity) getActivity())
                                                    .continueShutdown(true);
                                    }
                        }).onCreate();
    }
    

    This method return Dialog object that asks user if he/she wants to exit the application as you can see it doesn't make any sense to create an AlertDialog object by calling a constructor with too many arguments. Imagine if AlertDialog has such a constructor :

    AlertDialog ad = new AlertDialog(getActivity(), "Do you really want to exit?", 
                                     false, "No", .... )//and the list goes on 
    

    Compare this approach with onCreateDialog method I think onCreateDialog method wins right ?

提交回复
热议问题