📌  相关文章
📜  如何在 Android 中创建自定义 AlertDialog

📅  最后修改于: 2021-10-28 02:35:15             🧑  作者: Mango

有时在 AlertDialog 中,需要获取用户的输入或根据我们的要求进行自定义。所以我们创建了自定义的 AlertDialogs。这篇文章将展示如何自定义 AlertDialogs 并从中获取输入。

下面是上述方法的逐步实现:

  • 步骤 1:创建一个 XML 文件: custom_layout.xml 。在 custom_layout.xml 中添加以下代码。此代码定义警报对话框尺寸并在其中添加编辑文本
    
    
      
      
    
    
  • 第 2 步:activity_main.xml 中添加一个按钮。单击该按钮时将显示 AlertDialog 框。
    
    
      
        
  • 第 3 步:

    在要在此处显示自定义警报对话框的活动中添加custom_layout.xml ,它已添加到 MainActivity 中。Java。

    public class MainActivity
        extends AppCompatActivity {
      
        @Override
        protected void onCreate(
            Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
      
        public void showAlertDialogButtonClicked(View view)
        {
      
            // Create an alert builder
            AlertDialog.Builder builder
                = new AlertDialog.Builder(this);
            builder.setTitle("Name");
      
            // set the custom layout
            final View customLayout
                = getLayoutInflater()
                      .inflate(
                          R.layout.custom_layout,
                          null);
            builder.setView(customLayout);
      
            // add a button
            builder
                .setPositiveButton(
                    "OK",
                    new DialogInterface.OnClickListener() {
      
                        @Override
                        public void onClick(
                            DialogInterface dialog,
                            int which)
                        {
      
                            // send data from the
                            // AlertDialog to the Activity
                            EditText editText
                                = customLayout
                                      .findViewById(
                                          R.id.editText);
                            sendDialogDataToActivity(
                                editText
                                    .getText()
                                    .toString());
                        }
                    });
      
            // create and show
            // the alert dialog
            AlertDialog dialog
                = builder.create();
            dialog.show();
        }
      
        // Do something with the data
        // coming from the AlertDialog
        private void sendDialogDataToActivity(String data)
        {
            Toast.makeText(this,
                           data,
                           Toast.LENGTH_SHORT)
                .show();
        }
    }
    

输出: