【Android】运用Builder来创建Alertdialog


简述

直接在activity调用AlertDialog.Builder来创建一个dialog,不用单独去创建一个类,这个设计我感觉非常友好。考虑到实际安卓app的dialog需要完成的任务也不会太多,所以这个方法应该可以实现90%的需求了,比安 卓官方文档里面用正儿八经创建对话框的方法简便,话不多说,看看这个模式吧。

首先我们需要一个对话框的layout





    


        


        
    


    


    

用getLayoutInflater().inflate()方法找到在资源文件里找到layout

LinearLayout layout=(LinearLayout) getLayoutInflater().inflate(R.layout.dialog,null);

顺便设置一下文字,R.string.dlg_titleR.string.dlg_message是string资源里自己添加的项

TextView dialogTile=layout.findViewById(R.id.dialog_title);
TextView dialogMessage=layout.findViewById(R.id.dialog_message);
dialogTile.setText(R.string.dlg_title);
dialogMessage.setText(R.string.dlg_message);

是在这里添加->【Android】运用Builder来创建Alertdialog_第1张图片

建造这个对话框

 new AlertDialog.Builder(MainActivity.this).setView(layout)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                /*
                                点击确定按钮要做的事
                                */
                            }
                        })
                        .setNegativeButton("取消",null)//因为取消键只是关闭,所以不设监听
                        .setCancelable(true)//可以点对话框外部关闭对话框
                        .create()
                        .show();

以上三段代码都是在activity中直接写的,不用新建一个类,写出来也很短,感觉棒棒的。

转载于:https://www.cnblogs.com/QEStack/p/8146384.html

你可能感兴趣的:(【Android】运用Builder来创建Alertdialog)