如何设置Android对话框的MaxWidth?

问题描述

| 我有一个自定义样式的对话框,该对话框使用的是我在XML文件中定义的布局。我希望此对话框在纵向模式下填充屏幕的宽度,但在横向模式下仅填充400dip。 MaxWidth似乎是完成此操作的理想方法,但是我不知道如何为对话框样式或XML布局分配MaxWidth。     

解决方法

假设您使用下一个名为
layout/dialog_core.xml
的布局文件:
<?xml version=\"1.0\" encoding=\"utf-8\"?>
<LinearLayout 
    xmlns:android=\"http://schemas.android.com/apk/res/android\"
    android:layout_height=\"wrap_content\" 
    android:layout_width=\"fill_parent\" >

    //All your dialog views go here.... 

</LinearLayout>
然后,您可以再创建两个文件:
layout/dialog.xml
layout-land/dialog.xml
layout/dialog.xml
文件不会限制宽度:
<?xml version=\"1.0\" encoding=\"utf-8\"?>
<LinearLayout 
    xmlns:android=\"http://schemas.android.com/apk/res/android\"
    android:layout_height=\"wrap_content\" 
    android:layout_width=\"fill_parent\" >

    <include layout=\"@layout.dialog_core.xml\" />

</LinearLayout>
虽然您的
layout-land/dialog.xml
应该有宽度限制:
<?xml version=\"1.0\" encoding=\"utf-8\"?>
<LinearLayout 
    xmlns:android=\"http://schemas.android.com/apk/res/android\"
    android:layout_height=\"wrap_content\" 
    android:layout_width=\"fill_parent\"
    android:maxWidth=\"400dp\" >

    <include layout=\"@layout.dialog_core.xml\" />

</LinearLayout>
当然,您现在需要在代码中使用
R.layout.dialog
布局。 附言我将“ 9”仅用于示例目的。任何布局视图都可以。     ,您可以在此处找到实际的解决方案:为我的对话框设置最大宽度 答案是针对使用对话框主题的活动,但是考虑到它基于Window对象,因此将其适应对话框应该太复杂了。     ,在显示对话框之后,通过更改对话框的窗口布局,我为BottomSheetDialog实现了这一点:
private int maxWidthDp = 600;

public void showDialog(Context context) {
    BottomSheetDialog dialog = new BottomSheetDialog(context);
    // set up the dialog...
    dialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialogInterface) {
            Configuration configuration = context.getResources().getConfiguration();
            if (configuration.screenWidthDp > maxWidthDp) {
                // ensure maximum dialog size
                dialog.getWindow().setLayout(dpToPixels(maxWidthDp),-1);
            }
        }
    });
    dialog.show();
}
dpToPixels
是一个辅助功能,可将dp值转换为像素值,例如像这里https://stackoverflow.com/a/8399445/1396068     ,您是否尝试过在自定义xml中设置
android:minWidth
android:minHeight