我可以创建和显示一个自定义警报对话框很好,但即使这样,我有android:layout_width/height=“fill_parent”在对话xml中,它只和内容一样大。

我想要的是填充整个屏幕的对话框,除了20像素的填充。 然后,作为对话框一部分的图像将自动使用fill_parent拉伸到完整的对话框大小。


当前回答

下面的方法对我来说效果不错:

    <style name="MyAlertDialogTheme" parent="Base.Theme.AppCompat.Light.Dialog.Alert">
        <item name="windowFixedWidthMajor">90%</item>
        <item name="windowFixedWidthMinor">90%</item>
    </style>

(注:windowMinWidthMajor/Minor,如之前的答案所建议的,没有做到这一点。我的对话框不断改变大小取决于内容)

然后:

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.MyAlertDialogTheme);

其他回答

如果你使用对话片段,你可以用onResume方法。 这是Xamarin Android的代码,但我认为它很容易理解

public override void OnResume() 
{
    base.OnResume();
    var metrics = Resources.DisplayMetrics;

    double width = metrics.WidthPixels * 0.9;
    double height = metrics.HeightPixels * 0.6;

    this.Dialog.Window.SetLayout((int)width, (int)height);
    this.Dialog.Window.SetGravity(Android.Views.GravityFlags.Center);
}
public static WindowManager.LayoutParams setDialogLayoutParams(Activity activity, Dialog dialog)
    {
        try 
        {
            Display display = activity.getWindowManager().getDefaultDisplay();
            Point screenSize = new Point();
            display.getSize(screenSize);
            int width = screenSize.x;

            WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
            layoutParams.copyFrom(dialog.getWindow().getAttributes());
            layoutParams.width = (int) (width - (width * 0.07) ); 
            layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
            return layoutParams;
        } 
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }

你必须在显示之前设置对话框的高度和宽度(dialog.show())

所以,像这样做:

dialog.getWindow().setLayout(width, height);

//then

dialog.show()

我发现了一个非常简单易行的解决办法

    fun showDialog(){
    val dialog = Dialog(this@DialogActivity)
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
    dialog.setCancelable(false)
    dialog.setContentView(R.layout.custom_dialog)
    val txtTitle = dialog.findViewById<TextView>(R.id.txtTitle)
    val btn  = dialog.findViewById<Button>(R.id.button)

    btn.setOnClickListener {
        Toast.makeText(this,"test",Toast.LENGTH_SHORT).show()
    }
    txtTitle.setText("ali")
    dialog.show()

    val window = dialog.window
    window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.WRAP_CONTENT)
}
dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.WRAP_CONTENT);