IT박스

Android에서 기본 경고 대화 상자의 너비와 높이를 제어하는 ​​방법은 무엇입니까?

itboxs 2020. 11. 6. 07:59
반응형

Android에서 기본 경고 대화 상자의 너비와 높이를 제어하는 ​​방법은 무엇입니까?


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.

경고 창에서 레이아웃 매개 변수를 가져오고 수동으로 너비와 높이를 설정하는 방법은 무엇입니까?


토 코드에서만 약간의 변화는 후 레이아웃을 설정 show()방법 AlertDialog.

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);

Ok, 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();

레이아웃 후 크기를 조정하기 전에 먼저 대화에서 사용하는 스타일을 확인하십시오. 스타일 트리 세트에 아무것도 없는지 확인하십시오.

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

그런 경우 [테마 ResId를 사용하는 빌드 생성자] ( 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>

이것은 .getWindow().setLayout(width, height)뒤에 추가하여 작동합니다.show()

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);

장치 프레임을 기반으로 동적 너비와 높이를 추가하려면 이러한 계산을 수행하고 높이와 너비를 할당 할 수 있습니다.

 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));

추신 : 먼저 대화 상자를 표시 한 다음 창의 레이아웃 속성을 수정 해보십시오.


저처럼이 스레드를 찾을 수있는 사람들을 위해 여기에 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);

AlertDialog의 기본 높이 / 너비를 변경할 수 있는지 여부는 모르겠지만 이렇게하려면 자신 만의 사용자 지정 대화 상자를 만들어서 할 수 있다고 생각합니다. android:theme="@android:style/Theme.Dialog"활동에 대한 android manifest.xml 을 제공 하고 요구 사항에 따라 전체 레이아웃을 작성할 수 있습니다. Android 리소스 XML에서 사용자 지정 대화 상자의 높이와 너비를 설정할 수 있습니다.


동적이기 때문에 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화면 해상도에 따라 변경됩니다.

도움이되기를 바랍니다. 감사.


나는 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>

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())
    }
  }
}

짧은 메시지

긴 메시지

참고 URL : https://stackoverflow.com/questions/4406804/how-to-control-the-width-and-height-of-the-default-alert-dialog-in-android

반응형