首页 > 解决方案 > 调整警报对话框的大小

问题描述

我有一个 AlertDialog 提示用户在 EditText 中输入文本,但 AlertDialog 弹出窗口没有我需要的那么宽。这是它的样子: 在此处输入图像描述

我如何使它更宽?

这是我的代码的相关部分:

  AlertDialog.Builder alert = new AlertDialog.Builder(getContext(), R.style.AlertDialogCustom);
  // Using the following constructor produces a desirable width but 
  // the wrong theme colors
  // AlertDialog.Builder alert = new AlertDialog.Builder(getContext());

  final EditText edittext = new EditText(getContext());
  alert.setMessage("Enter Your Message");
  alert.setTitle("Enter Your Title");

  alert.setView(edittext);

  alert.setPositiveButton("Yes Option", new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int whichButton) {

    String YouEditTextValue = edittext.getText().toString();
   }
  });

  alert.setNegativeButton("No Option", new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int whichButton) {
    // what ever you want to do with No option.
   }
  });

  alert.show();

我对一个主题的尝试:

<style name="AlertDialogCustom" parent="Theme.AppCompat.Light.Dialog">
    <item name="android:textColor">@color/colorLightGray</item>
    <item name="android:typeface">monospace</item>
    <item name="android:textSize">10sp</item>
    <item name="android:windowBackground">@color/colorDarkerGray</item>
</style>

标签: androidandroid-layoutandroid-alertdialog

解决方案


根据您的需要设置自定义的 Windowmanager 布局参数,您应该一切顺利。在调用 dialog's 后执行此操作show(),例如:

alertDialog.show();
WindowManager.LayoutParams layoutParams = new 
WindowManager.LayoutParams();

layoutParams .copyFrom(alertDialog.getWindow().getAttributes());
layoutParams .width = 150;
layoutParams .height = 500;
layoutParams .x=-170;
layoutParams .y=100;
alertDialog.getWindow().setAttributes(layoutParams );

推荐阅读