35

このダイアログを指定するレイアウトで使用すると、次のダイアログが表示されますandroid:layout_width="match_parent"

小さなダイアログ

より広いダイアログが必要です。何か案は?

4

2 に答える 2

122

Windowダイアログが使用するオブジェクトを取得し、幅をリセットすることで、これを行うことができます。簡単な例を次に示します。

//show the dialog first
AlertDialog dialog = new AlertDialog.Builder(this)
        .setTitle("Test Dialog")
        .setMessage("This should expand to the full width")
        .show();
//Grab the window of the dialog, and change the width
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
Window window = dialog.getWindow();
lp.copyFrom(window.getAttributes());
//This makes the dialog take up the full width
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
window.setAttributes(lp);

これが最終結果です。細かい調整 (背景の変更など) が必要な場合は、ダイアログに対してさらに多くのスタイリングを行うことができます。過去にこれを行う必要があった場合、通常はこのメソッドを使用しsetView()、ビルダー クラスでダイアログで使用されるレイアウトをカスタマイズします。

例

于 2012-07-23T14:01:09.917 に答える
4

これを修正する別の方法は、次を使用することです。

import android.support.v7.app.AlertDialog;

それ以外の:

import android.app.AlertDialog;
于 2016-11-23T06:49:00.370 に答える