首页 文章

如何使警报对话框填充90%的屏幕大小?

提问于
浏览
248

我可以创建并显示一个自定义警报对话框,但即便如此,我在对话框xml中只有 android:layout_width/height="fill_parent" 它只有内容大 .

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

24 回答

  • 45

    我的答案是基于koma的,但它不需要覆盖onStart,只需要onCreateView,在创建新片段时,默认情况下几乎总是覆盖它 .

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.your_fragment_layout, container);
    
        Rect displayRectangle = new Rect();
        Window window = getDialog().getWindow();
        window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
    
        v.setMinimumWidth((int)(displayRectangle.width() * 0.9f));
        v.setMinimumHeight((int)(displayRectangle.height() * 0.9f));
    
        return v;
    }
    

    我在Android 5.0.1上测试过它 .

  • 2

    根据Android平台开发人员Dianne Hackborn在this讨论组帖子中,Dialogs将他们Window的顶级布局宽度和高度设置为 WRAP_CONTENT . 要使Dialog更大,可以将这些参数设置为 MATCH_PARENT .

    演示代码:

    AlertDialog.Builder adb = new AlertDialog.Builder(this);
        Dialog d = adb.setView(new View(this)).create();
        // (That new View is just there to have something inside the dialog that can grow big enough to cover the whole screen.)
    
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(d.getWindow().getAttributes());
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        d.show();
        d.getWindow().setAttributes(lp);
    

    请注意,在显示对话框后设置属性 . 系统在设置时很挑剔 . (我猜布局引擎必须在第一次显示对话框时设置它们 . )

    最好通过扩展Theme.Dialog来做到这一点,然后你不会让对话框自动采用适当的光明或黑暗主题或Honeycomb Holo主题 . 这可以根据http://developer.android.com/guide/topics/ui/themes.html#SelectATheme)完成

  • 48

    尝试将自定义对话框布局包装到 RelativeLayout 而不是 LinearLayout . 这对我有用 .

  • 3

    像对方建议的那样在对话框窗口上指定FILL_PARENT对我来说不起作用(在Android 4.0.4上),因为它只是拉伸黑色对话框背景以填满整个屏幕 .

    什么工作正常是使用最小显示值,但在代码中指定它,以便对话框占用屏幕的90% .

    所以:

    Activity activity = ...;
    AlertDialog dialog = ...;
    
    // retrieve display dimensions
    Rect displayRectangle = new Rect();
    Window window = activity.getWindow();
    window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
    
    // inflate and adjust layout
    LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View layout = inflater.inflate(R.layout.your_dialog_layout, null);
    layout.setMinimumWidth((int)(displayRectangle.width() * 0.9f));
    layout.setMinimumHeight((int)(displayRectangle.height() * 0.9f));
    
    dialog.setView(layout);
    

    通常,在大多数情况下仅调整宽度应该是足够的 .

  • 79

    在自定义视图xml中设置 android:minWidthandroid:minHeight . 这些可以强制警报不仅仅包装内容大小 . 使用这样的视图应该这样做:

    <LinearLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:minWidth="300dp" 
      android:minHeight="400dp">
      <ImageView
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:background="@drawable/icon"/>
    </LinearLayout>
    
  • 18
    dialog.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    
  • 2

    更简单就是这样做:

    int width = (int)(getResources().getDisplayMetrics().widthPixels*0.90);
    int height = (int)(getResources().getDisplayMetrics().heightPixels*0.90);
    
    alertDialog.getWindow().setLayout(width, height);
    
  • 4

    这里的所有其他答案都是有道理的,但它不符合Fabian的需求 . 这是我的解决方案 . 它可能不是完美的解决方案,但它适用于我 . 它显示一个全屏对话框,但您可以在顶部,底部,左侧或右侧指定填充 .

    首先将它放在res / values / styles.xml中:

    <style name="CustomDialog" parent="@android:style/Theme.Dialog">
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowBackground">@color/Black0Percent</item>
        <item name="android:paddingTop">20dp</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:backgroundDimEnabled">false</item>
        <item name="android:windowIsFloating">false</item>
    </style>
    

    如你所见,我在那里 android:paddingTop= 20dp 基本上是你需要的 . android:windowBackground = @color/Black0Percent 只是我在color.xml上声明的颜色代码

    res / values / color.xml

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    <color name="Black0Percent">#00000000</color>
    </resources>
    

    该Color代码仅用作虚拟对象,用0%透明度颜色替换Dialog的默认窗口背景 .

    接下来构建自定义对话框布局res / layout / dialog.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/dialoglayout"
        android:layout_width="match_parent"
        android:background="@drawable/DesiredImageBackground"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    
        <EditText
            android:id="@+id/edittext1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:textSize="18dp" />
    
        <Button
            android:id="@+id/button1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Dummy Button"
            android:textSize="18dp" />
    
    </LinearLayout>
    

    最后,我们的对话框设置了使用dialog.xml的自定义视图:

    Dialog customDialog;
    LayoutInflater inflater = (LayoutInflater) getLayoutInflater();
    View customView = inflater.inflate(R.layout.dialog, null);
    // Build the dialog
    customDialog = new Dialog(this, R.style.CustomDialog);
    customDialog.setContentView(customView);
    customDialog.show();
    

    Conclusion: 我试图在名为CustomDialog的styles.xml中覆盖对话框的主题 . 它会覆盖Dialog窗口布局,让我有机会设置填充并更改背景的不透明度 . 它可能不是完美的解决方案,但我希望它可以帮助你.. :)

  • 2

    您可以使用百分比(JUST)窗口对话框宽度 .

    从Holo Theme看这个例子:

    <style name="Theme.Holo.Dialog.NoActionBar.MinWidth">
        <item name="android:windowMinWidthMajor">@android:dimen/dialog_min_width_major</item>
        <item name="android:windowMinWidthMinor">@android:dimen/dialog_min_width_minor</item>
    </style>
    
     <!-- The platform's desired minimum size for a dialog's width when it
         is along the major axis (that is the screen is landscape).  This may
         be either a fraction or a dimension. -->
    <item type="dimen" name="dialog_min_width_major">65%</item>
    

    您需要做的就是扩展此主题并将“Major”和“Minor”的值更改为90%而不是65% .

    问候 .

  • 6

    以下工作对我来说很好:

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

    实际90%计算的解决方案:

    @Override public void onStart() {
       Dialog dialog = getDialog();
       if (dialog != null) {
         dialog.getWindow()
            .setLayout((int) (getScreenWidth(getActivity()) * .9), ViewGroup.LayoutParams.MATCH_PARENT);
       }
    }
    

    其中 getScreenWidth(Activity activity) 定义如下(最好放在Utils类中):

    public static int getScreenWidth(Activity activity) {
       Point size = new Point();
       activity.getWindowManager().getDefaultDisplay().getSize(size);
       return size.x;
    }
    
  • 21

    那么,你必须先设置你的对话框的高度和宽度才能显示它(dialog.show())

    所以,做这样的事情:

    dialog.getWindow().setLayout(width, height);
    
    //then
    
    dialog.show()
    
  • 14

    到目前为止我能想到的最简单的方式 -

    如果您的对话框是由垂直LinearLayout制作的,只需添加一个“高度填充”虚拟视图,它将占据屏幕的整个高度 .

    例如 -

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:weightSum="1">
    
        <EditText
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:id="@+id/editSearch" />
    
        <ListView
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:id="@+id/listView"/>
    
    
       <!-- this is a dummy view that will make sure the dialog is highest -->
       <View
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:layout_weight="1"/>
    
    </LinearLayout>
    

    注意LinearLayout属性中的 android:weightSum="1" 和虚拟视图属性中的 android:layout_weight="1"

  • 2

    那么,你必须先设置你的对话框的高度和宽度才能显示它(dialog.show())

    所以,做这样的事情:

    dialog.getWindow().setLayout(width, height);
    
    //then
    
    dialog.show()
    

    获取此代码,我做了一些更改:

    dialog.getWindow().setLayout((int)(MapGeaGtaxiActivity.this.getWindow().peekDecorView().getWidth()*0.9),(int) (MapGeaGtaxiActivity.this.getWindow().peekDecorView().getHeight()*0.9));
    

    但是,当设备改变其位置时,对话框大小可能会改变 . 当指标发生变化时,您可能需要自己处理 . PD:peekDecorView,暗示活动中的布局已正确初始化,否则您可以使用

    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    int height = metrics.heightPixels;
    int wwidth = metrics.widthPixels;
    

    为了获得屏幕尺寸

  • 75

    初始化对话框对象并设置内容视图后 . 这样做,享受 .

    (如果我将宽度设置为90%,高度设置为70%,因为宽度为90%,它将位于工具栏上方)

    DisplayMetrics displaymetrics = new DisplayMetrics();
    getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int width = (int) ((int)displaymetrics.widthPixels * 0.9);
    int height = (int) ((int)displaymetrics.heightPixels * 0.7);
    d.getWindow().setLayout(width,height);
    d.show();
    
  • 15

    这是我的自定义对话框的变体宽度:

    DisplayMetrics displaymetrics = new DisplayMetrics();
    mActivity.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int width = (int) (displaymetrics.widthPixels * (ThemeHelper.isPortrait(mContext) ? 0.95 : 0.65));
    
    WindowManager.LayoutParams params = getWindow().getAttributes();
    params.width = width;
    getWindow().setAttributes(params);
    

    因此,取决于设备方向( ThemeHelper.isPortrait(mContext) )对话框's width will be either 95% (for portrait mode) or 65% (for landscape). It' s,作者要求的更多,但它可能对某人有用 .

    您需要创建一个从Dialog扩展的类,并将此代码放入 onCreate(Bundle savedInstanceState) 方法中 .

    对于对话框的高度,代码应与此类似 .

  • 4
    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;
            }
        }
    
  • 333

    以上许多答案都很好,但没有一个对我有用 . 所以我把@nmr的答案结合起来得到了这个 .

    final Dialog d = new Dialog(getActivity());
            //  d.getWindow().setBackgroundDrawable(R.color.action_bar_bg);
            d.requestWindowFeature(Window.FEATURE_NO_TITLE);
            d.setContentView(R.layout.dialog_box_shipment_detail);
    
            WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE); // for activity use context instead of getActivity()
            Display display = wm.getDefaultDisplay(); // getting the screen size of device
            Point size = new Point();
            display.getSize(size);
            int width = size.x - 20;  // Set your heights
            int height = size.y - 80; // set your widths
    
            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(d.getWindow().getAttributes());
    
            lp.width = width;
            lp.height = height;
    
            d.getWindow().setAttributes(lp);
            d.show();
    
  • -1
    ...
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        Dialog d = builder.create(); //create Dialog
        d.show(); //first show
    
        DisplayMetrics metrics = new DisplayMetrics(); //get metrics of screen
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int height = (int) (metrics.heightPixels*0.9); //set height to 90% of total
        int width = (int) (metrics.widthPixels*0.9); //set width to 90% of total
    
        d.getWindow().setLayout(width, height); //set layout
    
  • 2

    获取设备宽度:

    public static int getWidth(Context context) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        WindowManager windowmanager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowmanager.getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    }
    

    然后使用它来制作对话框90%的设备,

    Dialog filterDialog = new Dialog(context, R.style.searchsdk_FilterDialog);
    
    filterDialog.setContentView(R.layout.searchsdk_filter_popup);
    initFilterDialog(filterDialog);
    filterDialog.setCancelable(true);
    filterDialog.getWindow().setLayout(((getWidth(context) / 100) * 90), LinearLayout.LayoutParams.MATCH_PARENT);
    filterDialog.getWindow().setGravity(Gravity.END);
    filterDialog.show();
    
  • 7

    这是一个对我有用的简短答案(在API 8和API 19上测试过) .

    Dialog mDialog;
    View   mDialogView;
    ...
    // Get height
    int height = mDialog.getWindow()
    .getWindowManager().getDefaultDisplay()
    .getHeight();
    
    // Set your desired padding (here 90%)
    int padding = height - (int)(height*0.9f);
    
    // Apply it to the Dialog
    mDialogView.setPadding(
    // padding left
    0,
    // padding top (90%)
    padding, 
    // padding right
    0, 
    // padding bottom (90%)
    padding);
    
  • 112

    您需要使用样式@ style.xml(如CustomDialog)来显示可自定义的对话框 .

    <style name="CustomDialog" parent="@android:style/Theme.DeviceDefault.Light.Dialog">
            <item name="android:windowIsTranslucent">true</item>
            <item name="android:windowBackground">@color/colorWhite</item>
            <item name="android:editTextColor">@color/colorBlack</item>
            <item name="android:windowContentOverlay">@null</item>
            <item name="android:windowNoTitle">true</item>
            <item name="android:backgroundDimEnabled">true</item>
            <item name="android:windowIsFloating">true</item>
            <item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
        </style>
    

    并在Activity.java中使用此样式

    Dialog dialog= new Dialog(Activity.this, R.style.CustomDialog);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setContentView(R.layout.custom_dialog);
    

    你的custom_dialog.xml应该在你的布局目录中

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="10dp"
        android:paddingRight="10dp">
    
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text=""
            android:textSize="20dp"
            android:id="@+id/tittle_text_view"
            android:textColor="@color/colorBlack"
            android:layout_marginTop="20dp"
            android:layout_marginLeft="10dp"/>
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginLeft="20dp"
            android:layout_marginBottom="10dp"
            android:layout_marginTop="20dp"
            android:layout_marginRight="20dp">
    
            <EditText
                android:id="@+id/edit_text_first"
                android:layout_width="50dp"
                android:layout_height="match_parent"
                android:hint="0"
                android:inputType="number" />
    
            <TextView
                android:id="@+id/text_view_first"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_marginLeft="5dp"
                android:gravity="center"/>
    
            <EditText
                android:id="@+id/edit_text_second"
                android:layout_width="50dp"
                android:layout_height="match_parent"
                android:hint="0"
                android:layout_marginLeft="5dp"
                android:inputType="number" />
    
            <TextView
                android:id="@+id/text_view_second"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_marginLeft="5dp"
                android:gravity="center"/>
    
        </LinearLayout>
    
    </LinearLayout>
    
  • 0
    dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.WRAP_CONTENT);
    
  • -1
    final AlertDialog alertDialog;
    
        LayoutInflater li = LayoutInflater.from(mActivity);
        final View promptsView = li.inflate(R.layout.layout_dialog_select_time, null);
    
        RecyclerView recyclerViewTime;
        RippleButton buttonDone;
    
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mActivity);
        alertDialogBuilder.setView(promptsView);
    
        // create alert dialog
        alertDialog = alertDialogBuilder.create();
    
        /**
         * setting up window design
         */
        alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    
    
        alertDialog.show();
    
        DisplayMetrics metrics = new DisplayMetrics(); //get metrics of screen
        mActivity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int height = (int) (metrics.heightPixels * 0.9); //set height to 90% of total
        int width = (int) (metrics.widthPixels * 0.9); //set width to 90% of total
    
        alertDialog.getWindow().setLayout(width, height); //set layout
        recyclerViewTime = promptsView.findViewById(R.id.recyclerViewTime);
    
    
        DialogSelectTimeAdapter dialogSelectTimeAdapter = new DialogSelectTimeAdapter(this);
        RecyclerView.LayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerViewTime.setLayoutManager(linearLayoutManager);
        recyclerViewTime.setAdapter(dialogSelectTimeAdapter);
    
        buttonDone = promptsView.findViewById(R.id.buttonDone);
        buttonDone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
    
                alertDialog.dismiss();
    
            }
        });
    

相关问题