【问题标题】:How to control the width and height of the default Alert Dialog in Android?如何控制Android中默认Alert Dialog的宽度和高度?
【发布时间】:2011-05-23 08:25:08
【问题描述】:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Title");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
            }
        });
        AlertDialog alert = builder.create();

我正在使用上面的代码来显示一个警报对话框。默认情况下,它以宽度填充屏幕,以高度填充 wrap_content。
如何控制默认警报对话框的宽度和高度?
我试过了:

alert.getWindow().setLayout(100,100); // It didn't work.

如何获取警报窗口的布局参数并手动设置宽度和高度?

【问题讨论】:

    标签: android android-widget


    【解决方案1】:

    只是Sat Code稍有改动,在AlertDialogshow()方法之后设置布局。

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setView(layout);
    builder.setTitle("Title");
    alertDialog = builder.create();
    alertDialog.show();
    alertDialog.getWindow().setLayout(600, 400); //Controlling width and height.
    

    或者你可以按照我的方式去做。

    alertDialog.show();
    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    
    lp.copyFrom(alertDialog.getWindow().getAttributes());
    lp.width = 150;
    lp.height = 500;
    lp.x=-170;
    lp.y=100;
    alertDialog.getWindow().setAttributes(lp);
    

    【讨论】:

    • @ingo:是的,您可以,创建一个属于对话框的 xml,并在该 xml 中设计您的文本,如 dialog.setContentView(R.layout.dialog);在 xml 中你可以对文本做任何事情。
    • @PiyushMishra 如何设置支持所有设备的heightwidth
    • +1 for after show()... 在这里呆了 2 个小时,直到那个时候才能让它工作。
    • @PratikButani 它只是一个示例,对于动态高度,您需要编写某些算法,例如首先计算屏幕的高度和宽度,然后根据它您可以细分对话框的高度和宽度以及它的位置。
    • 在调用方法 show 之后更改大小很重要。我花了很长时间才意识到这一点。
    【解决方案2】:

    好的,我可以使用 Builder 类来控制宽度和高度。 我用过

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setView(layout);
    builder.setTitle("Title");
    AlertDialog alertDialog = builder.create();
    alertDialog.getWindow().setLayout(600, 400); //Controlling width and height.
    alertDialog.show();
    

    【讨论】:

    • 优秀的捕获。在 create() 之后 WAY 比在 show() 之后更好,尤其是在使用 DialogFragments 时!
    • 你没有使用builder类来改变宽度/高度,只是alertDialog对象
    • 它在创作和演出之间对我不起作用,但只有在演出之后才起作用。
    • 应该在 on show 监听器中设置窗口宽度。
    【解决方案3】:

    对于那些像我一样会发现这个线程的人,这里是 IMO 更好的解决方案(注意 70% 设置对话框的最小宽度,以屏幕宽度的百分比表示):

    <style name="my_dialog" parent="Theme.AppCompat.Dialog.Alert">
        <item name="windowMinWidthMajor">70%</item>
        <item name="windowMinWidthMinor">70%</item>
    </style>
    

    然后将此样式应用于对话框:

    AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.my_dialog);
    

    【讨论】:

    • 在样式中使用百分比比以编程方式制作要容易得多
    • 不工作。即使在此样式之后也是相同的宽度。
    【解决方案4】:

    在尝试调整布局后的大小之前,请先检查对话框使用的样式。确保样式树中没有任何内容

    <item name="windowMinWidthMajor">...</item>
    <item name="windowMinWidthMinor">...</item>
    

    如果发生这种情况,只需将您自己的样式提供给 [接受 themeResId](http://developer.android.com/reference/android/app/AlertDialog.Builder.html#AlertDialog.Builder(android.content.Context, int)) 可用 API 11+ 的构建器构造函数即可

    <style name="WrapEverythingDialog" parent=[whatever you were previously using]>
        <item name="windowMinWidthMajor">0dp</item>
        <item name="windowMinWidthMinor">0dp</item>
    </style>
    

    【讨论】:

    • 谢谢,比编程简单得多。
    • 如何找到对话框使用的主题?我只能猜测。
    【解决方案5】:

    show() 之后添加.getWindow().setLayout(width, height) 也可以这样做

    alertDialogBuilder
                .setMessage("Click yes to exit!")
                .setCancelable(false)
                .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        // if this button is clicked, close
                        // current activity
                        MainActivity.this.finish();
                    }
                  })
                .setNegativeButton("No",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        // if this button is clicked, just close
                        // the dialog box and do nothing
                        dialog.cancel();
                    }
                }).show().getWindow().setLayout(600,500);
    

    【讨论】:

    • 无法让它以任何方式工作,除了这种方式,所以为你 +1。谢谢!
    【解决方案6】:

    如果您想根据您的设备框架添加动态宽度和高度,您可以进行这些计算并分配高度和宽度。

     AlertDialog.Builder builderSingle = new 
     AlertDialog.Builder(getActivity());
     builderSingle.setTitle("Title");
    
     final AlertDialog alertDialog = builderSingle.create();
     alertDialog.show();
    
     Rect displayRectangle = new Rect();
     Window window = getActivity().getWindow();
    
     window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
    
     alertDialog.getWindow().setLayout((int)(displayRectangle.width() * 
     0.8f), (int)(displayRectangle.height() * 0.8f));
    

    P.S : 先显示对话框,然后尝试修改窗口的布局属性

    【讨论】:

    • 不想改变高度怎么办?
    • "P.S : 先显示对话框,然后尝试修改窗口的布局属性" 像魅力一样工作!
    【解决方案7】:

    感谢Sid 的回答,因为它是动态的,但我想添加一些东西。

    如果你只想改变宽度,高度会保持原样。

    我做了以下事情:

        // All process of AlertDialog
        AlertDialog alert = builder.create();
        alert.show();
    
        // Creating Dynamic
        Rect displayRectangle = new Rect();
    
        Window window = getActivity().getWindow();
        window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
        alert.getWindow().setLayout((int) (displayRectangle.width() *
                0.8f), alert.getWindow().getAttributes().height);
    

    这里我使用alert.getWindow().getAttributes().height 来保持AlertDialog 的高度,而Width 将根据屏幕分辨率进行更改。

    希望它会有所帮助。谢谢。

    【讨论】:

      【解决方案8】:

      我不知道您是否可以更改 AlertDialog 的默认高度/宽度,但如果您想这样做,我认为您可以通过创建自己的自定义对话框来实现。您只需要在 android manifest.xml 中为您的活动提供android:theme="@android:style/Theme.Dialog",并可以根据您的要求编写整个布局。您可以从 Android 资源 XML 设置自定义对话框的高度和宽度。

      【讨论】:

      • 它可能有效,但我不想添加其他活动。我发布了我使用的解决方案。谢谢。
      • 是的,上述方法也适用于以弹出式样式显示项目或说警报对话框样式。刚刚在其中一个项目中尝试过。
      • 只是比较了 2 种方式,1. 使用 AlertDialog.builder 和另一种 2. 带有主题 Dialog 的活动,第二个是更好的解决方案,唯一的缺点是如果必须将一些结果发送回后台视图,必须使用 startActivityForResult ,因为后台活动中的元素(视图)不可用。
      【解决方案9】:

      我认为 tir38 的答案是最干净的解决方案。请记住,如果您使用 android.app.AlerDialog 和 holo 主题,您的样式应该如下所示

      <style name="WrapEverythingDialog" parent=[holo theme ex. android:Theme.Holo.Dialog]>
          <item name="windowMinWidthMajor">0dp</item>
          <item name="windowMinWidthMinor">0dp</item>
      </style>
      

      如果使用带有 AppCompat 主题的 support.v7.app.AlertDialog 或 androidx.appcompat.app.AlertDialog 你的样式应该是这样的

      <style name="WrapEverythingDialog" parent=[Appcompat theme ex. Theme.AppCompat.Light.Dialog.Alert]>
          <item name="android:windowMinWidthMajor">0dp</item>
          <item name="android:windowMinWidthMinor">0dp</item>
      </style>
      

      【讨论】:

      • 你刚刚复制了 tir38 的答案
      【解决方案10】:
      longButton.setOnClickListener {
        show(
          "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
            "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
            "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
            "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
            "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
            "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
            "1234567890-12345678901234567890123456789012345678901234567890"
        )
      }
      
      shortButton.setOnClickListener {
        show(
          "1234567890\n" +
            "1234567890-12345678901234567890123456789012345678901234567890"
        )
      }
      

      private fun show(msg: String) {
        val builder = AlertDialog.Builder(this).apply {
          setPositiveButton(android.R.string.ok, null)
          setNegativeButton(android.R.string.cancel, null)
        }
      
        val dialog = builder.create().apply {
          setMessage(msg)
        }
        dialog.show()
      
        dialog.window?.decorView?.addOnLayoutChangeListener { v, _, _, _, _, _, _, _, _ ->
          val displayRectangle = Rect()
          val window = dialog.window
          v.getWindowVisibleDisplayFrame(displayRectangle)
          val maxHeight = displayRectangle.height() * 0.6f // 60%
      
          if (v.height > maxHeight) {
            window?.setLayout(window.attributes.width, maxHeight.toInt())
          }
        }
      }
      

      【讨论】:

        【解决方案11】:

        我花了很长时间才让它按我想要的方式工作。这段代码使得几乎整个屏幕宽度都充满了我想要的对话框......

        public class GenericDialogFragment extends DialogFragment {
            
        ...
        
            public void show() {
                super.show(fragmentManager, null);
        
                // Wait for the dialog to be created before resizing
                // Source: https://stackoverflow.com/questions/8456143/dialogfragment-getdialog-returns-null
                fragmentManager.executePendingTransactions();
        
                // Creating dynamic size
                // Source: https://stackoverflow.com/questions/4406804/how-to-control-the-width-and-height-of-the-default-alert-dialog-in-android
                Rect displayRectangle = new Rect();
        
                Window window = mActivity.getWindow();
                window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
        
                if (getDialog() != null) {
                    getDialog().getWindow().setLayout(
                            (int) (displayRectangle.width() * 1.0f),
                            getDialog().getWindow().getAttributes().height);
                }
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2016-09-29
          • 2011-08-17
          • 1970-01-01
          • 2021-04-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多