将EditTexts添加到警报对话框-缺少代码?

问题描述 投票:0回答:1

我偶然发现了这段代码,里面是如何创建一个带有两个编辑文本的警报对话框。运行后,当我按该项目时,没有弹出警报。我猜想我缺少一些基本语法,知道吗?

final AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
                    alert.setTitle("Hi there!");
                    alert.setMessage("Got a question? we'd love to hear from you. Send us a message and we'll respond ASAP");

                    LinearLayout layout = new LinearLayout(MainActivity.this);
                    layout.setOrientation(LinearLayout.VERTICAL);

                    final EditText titleBox = new EditText(MainActivity.this);
                    titleBox.setHint("Title");
                    layout.addView(titleBox); 

                    final EditText descriptionBox = new EditText(MainActivity.this);
                    descriptionBox.setHint("Description");
                    layout.addView(descriptionBox); 

                    alert.setView(layout);
                    alert.setPositiveButton("SEND", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // sending the mail from user to harel's mail address
                            Intent i = new Intent(Intent.ACTION_SEND);
                            i.setType("message/rfc822");
                            i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"<mail here>"});
                            i.putExtra(Intent.EXTRA_SUBJECT, titleBox.getText());
                            i.putExtra(Intent.EXTRA_TEXT   , descriptionBox.getText());
                            try {
                                startActivity(Intent.createChooser(i, "Send mail..."));
                            } catch (android.content.ActivityNotFoundException ex) {
                                Toast.makeText(MainActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });

                    AlertDialog alert1 = alert.create();
                    alert1.show();
android android-alertdialog
1个回答
0
投票

您在问题中输入的代码运行正常(缺少对话框按钮)。尝试检查是否在按钮(该项目)上设置了点击侦听器以打开对话框,如下例所示:

buttonExample.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //TODO - your dialog code here.
        }
    });

还有一个小技巧:您无需创建alert1。只需使用此代码更改最后几行:

alert.create();
alert.show();

希望这对您有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.