alertdialog

AlertDialog弹窗大小如何调整

小樊
87
2024-09-04 16:51:25
栏目: 编程语言

AlertDialog 是 Android 中用于显示对话框的一个类

  1. 使用 WindowManager.LayoutParams 设置对话框大小:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Hello World!");
AlertDialog alertDialog = builder.create();

// 在显示对话框之前设置大小
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
layoutParams.copyFrom(alertDialog.getWindow().getAttributes());
layoutParams.width = 500; // 设置宽度,单位为像素
layoutParams.height = 300; // 设置高度,单位为像素
alertDialog.getWindow().setAttributes(layoutParams);

alertDialog.show();
  1. 使用 setView() 方法自定义对话框布局并设置大小:
AlertDialog.Builder builder = new AlertDialog.Builder(this);

// 创建一个自定义布局并设置大小
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(500, 300);
TextView textView = new TextView(this);
textView.setText("Hello World!");
linearLayout.addView(textView, layoutParams);

// 将自定义布局添加到对话框中
builder.setView(linearLayout);

AlertDialog alertDialog = builder.create();
alertDialog.show();

这两种方法都可以实现调整 AlertDialog 弹窗的大小。请根据你的需求选择合适的方法。注意,上述代码中的宽度和高度单位为像素,你可能需要根据屏幕密度进行转换。

0
看了该问题的人还看了