【问题标题】:How to make an alert dialog fill 90% of screen size?如何使警报对话框填充 90% 的屏幕尺寸?
【发布时间】:2011-01-19 08:59:33
【问题描述】:

我可以很好地创建和显示自定义警报对话框,但即便如此,我在对话框 xml 中有android:layout_width/height="fill_parent",它也只是与内容一样大。

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

【问题讨论】:

    标签: android dialog


    【解决方案1】:

    我发现一个非常简单易用的解决方法

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

    【讨论】:

      【解决方案2】:

      让你的对话成为一个活动。 3个步骤

      第 1 步: 将其中之一放在styles.xml中

      样式一: 我喜欢这个,因为您可以将父主题更改为您在应用程序的其余部分使用的主题名称。

      <style name="DialogTheme" parent="Theme.AppCompat.Light.NoActionBar">
          <item name="android:windowIsTranslucent">true</item>
          <item name="android:windowBackground">@color/transparent</item>
          <item name="android:windowIsFloating">true</item>
          <item name="android:windowMinWidthMajor">90%</item>
          <item name="android:windowMinWidthMinor">90%</item>
      </style>
      

      样式二:

      <style name="DialogTheme" parent="Theme.AppCompat.Dialog">
          <item name="android:windowMinWidthMajor">90%</item>
          <item name="android:windowMinWidthMinor">90%</item>
      </style>
      

      第 2 步: 然后把这个放到AndroidManifest.xml中

      <activity
          android:name="com.example.YourApp.DialogActivity"
          android:theme="@style/DialogTheme" />
      

      第 3 步: 并确保在 activity_dialog.xml 中有主布局宽度 fill_parent 或 match_parent

      <?xml version="1.0" encoding="utf-8"?>
      <androidx.constraintlayout.widget.ConstraintLayout 
          xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          xmlns:tools="http://schemas.android.com/tools"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          tools:context=".DialogActivity">
      
      </androidx.constraintlayout.widget.ConstraintLayout>
      

      【讨论】:

        【解决方案3】:

        部分基于 Anand 的回答。这对我有用:

        override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
            val fragmentActivity = requireActivity()
            val v = View.inflate(context, R.layout.fragment_about_dialog, null)
            val dialog = Dialog(fragmentActivity)
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
            dialog.setContentView(v)
        
            val wm = fragmentActivity.getSystemService(Context.WINDOW_SERVICE) as WindowManager 
        
            val display = if (VERSION.SDK_INT >= VERSION_CODES.R) {
                fragmentActivity.display
            } else {
                wm.defaultDisplay // deprecated in API 30
            }
        
            val size = Point()
            display?.getSize(size)
        
            val width = size.x - 50
            val height = size.y - 50
            val lp = WindowManager.LayoutParams()
            lp.copyFrom(dialog.window?.attributes)
            lp.width = width
            lp.height = height
            dialog.show()
            dialog.window?.attributes = lp
            
            return dialog
        }
        

        对于对话框布局使用了约束布局:

        <androidx.constraintlayout.widget.ConstraintLayout 
                android:id="@+id/dialogLayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
            ...
        </androidx.constraintlayout.widget.ConstraintLayout>
        

        结果:

        这在更改屏幕方向时效果很好。

        【讨论】:

          【解决方案4】:

          如果您使用对话框片段,您可以在 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);
          }
          

          【讨论】:

            【解决方案5】:

            试试这个:

            dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            

            【讨论】:

            • OP 要求 90%,而不是全屏
            【解决方案6】:

            您需要使用样式@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>
            

            【讨论】:

              【解决方案7】:

              只需给 AlertDialog 这个主题

              <style name="DialogTheme" parent="Theme.MaterialComponents.Light.Dialog.MinWidth">
                  <item name="colorPrimary">@color/colorPrimary</item>
                  <item name="android:windowMinWidthMajor">90%</item>
                  <item name="android:windowMinWidthMinor">90%</item>
              </style>
              

              【讨论】:

                【解决方案8】:

                如果您使用约束布局,您可以在其中设置任何视图,以填充屏幕的百分比:

                layout_constraintWidth_percent="0.8"

                因此,例如,如果您在对话框中有一个 ScrollView,并且您想将其设置为屏幕高度的百分比。应该是这样的:

                <ScrollView
                            android:id="@+id/scrollView"
                            android:layout_width="match_parent"
                            android:layout_height="0dp"
                            app:layout_constraintHeight_percent="0.8">
                

                希望它对某人有所帮助!

                【讨论】:

                  【解决方案9】:

                  获取设备宽度:

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

                  【讨论】:

                    【解决方案10】:
                        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();
                    
                            }
                        });
                    

                    【讨论】:

                    • 自定义对话框,对话框自定义高度
                    【解决方案11】:

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

                    【讨论】:

                    • 它也适合我。谁能解释一下原因!!
                    • RelativeLayout 应该是这样工作的,还是可能会消失的快乐事故?
                    • 现在是 2019 年,这仍然有效。干杯!确实应该是公认的答案。
                    • @cvarsendan 你能解释一下答案吗?这对我有用。谢谢!
                    • 我的天啊,我的 RecyclerView 从不显示全高,或者它的高度总是 0,然后在尝试了许多解决方案一天后,它可以完美地工作。为什么是RelativeLayout 而其他呢?
                    【解决方案12】:
                    dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.WRAP_CONTENT);
                    

                    【讨论】:

                      【解决方案13】:

                      实际 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;
                      }
                      

                      【讨论】:

                      • 对于一个应该像对话框一样工作的 appcompatactivity 就像魅力一样
                      • 我的数组索引越界了:(
                      • @Dr.aNdRO 怎么样?哪条线?你确定是这段代码而不是 smt else?
                      • .setLayout() 我在这条线上,当我将它更改为 WRAP CONTENT 时,它工作正常
                      【解决方案14】:

                      在初始化对话对象并设置内容视图之后。这样做并享受。

                      (如果我将宽度设置为 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】:

                        以下对我来说很好用:

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

                        【讨论】:

                        • 迄今为止的最佳答案。非常适合我!
                        • 我想知道:如何通过代码获取这些以百分比设置的特殊维度的值?
                        【解决方案16】:
                            ...
                            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
                        

                        【讨论】:

                        • 在设置布局之前显示对话框对我有用。
                        【解决方案17】:

                        这样做更简单:

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

                        【讨论】:

                        • 小注:getResources() 在 Activity 上下文中可用。
                        • 这个答案对于在设备旋转后尝试在onCreate 中重新创建对话框的场景非常有帮助。在这种情况下,我们不能依赖布局中任何东西的宽度/高度,因为它还没有被创建;但设备的物理宽度/高度仍然可用。
                        • 如果你只想改变一个维度,传递ViewGroup.LayoutParams.WRAP_CONTENT作为参数之一
                        • 这对我来说是最好的解决方案。
                        • 最佳、最简单的解决方案
                        【解决方案18】:

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

                        如果您的对话框是由垂直 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"

                        【讨论】:

                        • 不错!这使我的 webview 不会从非常短的开始并在 onPageFinished 之后扩展到全高。赞一个!
                        【解决方案19】:

                        根据 Android 平台开发人员 Dianne Hackborn 在this 讨论组帖子中的说法,Dialogs 将其 Window 的顶级布局宽度和高度设置为 WRAP_CONTENT。要使对话框更大,您可以将这些参数设置为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 来做到这一点,这样你就不必玩什么时候调用 setAttributes 的猜谜游戏了。 (虽然让对话框自动采用适当的浅色或深色主题,或者 Honeycomb Holo 主题需要更多的工作。可以根据http://developer.android.com/guide/topics/ui/themes.html#SelectATheme 完成)

                        【讨论】:

                        • 无论是我不明白答案,还是对我不起作用。
                        • 对话框的 wrap_content 宽度似乎不是真的。事情变得更窄并被切断。对话框似乎设置为某个最大预定宽度。
                        • 我不明白这如何回答这个问题? @nmr 建议的代码是否使对话框占屏幕的 90%?因为我没看到。对话框只是设置为 fill_width,所以是 100%,而不是 90%,对吧?
                        • @Ted,AlertDialog 使用的主题有边距。所以结果没有到达屏幕的边缘,它填充了大约 90%。 (绝对不完全是 90%,只是审美上的近似 90%)
                        • 只调用 d.getWindow().getAttributes().width = WindowManager.LayoutParams.FILL_PARENT;在调用 show() 之前可以解决问题。另外,由于对话框的背景变得不透明,因此给定方法存在一些问题。删除 copyFrom(() 后,问题就自行解决了。
                        【解决方案20】:

                        上面的许多答案都很好,但没有一个完全适合我。所以我结合了@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();
                        

                        【讨论】:

                          【解决方案21】:

                          这里的所有其他答案都是有道理的,但它没有满足 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>
                          

                          该颜色代码只是用作将对话框的默认窗口背景替换为透明度为 0% 的颜色。

                          接下来构建自定义对话框布局 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();
                          

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

                          【讨论】:

                          • 它适用于 jellybean 现在我无法在其他 bulids 上测试它
                          • 似乎是最干净、最优雅的解决方案。适用于 Kitkat 4.4 和 4.3。
                          • 我有一个自定义对话框,在我看到这个之前没有任何效果,当你这样做时,自定义对话框(扩展 DialogFragment)上的所有魔法都会出现:Dialog customDialog = new Dialog(context, STYLE); 谢谢,真的,谢谢。
                          • 很高兴知道它有帮助:)
                          • 这就像对话窗口的魅力! (您也可以定义一个 Black60Percent 以使原始窗口变灰)不幸的副作用是我在对话框中的所有视图都继承了我为对话框设置的填充......
                          【解决方案22】:

                          好吧,你必须在显示这个之前设置你的对话框的高度和宽度( 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,表示activity中的布局已经正确初始化,否则你可以使用

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

                          为了得到屏幕尺寸

                          【讨论】:

                            【解决方案23】:

                            我的回答是基于 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 上测试过了。

                            【讨论】:

                              【解决方案24】:

                              这是一个对我有用的简短答案(在 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);
                              

                              【讨论】:

                                【解决方案25】:

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

                                从 Holo 主题中查看这个示例:

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

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

                                问候。

                                【讨论】:

                                • 要在对话框中使用它,只需在对话框构建器构造函数中传递您的自定义样式:)
                                【解决方案26】:
                                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;
                                        }
                                    }
                                

                                【讨论】:

                                  【解决方案27】:

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

                                  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)),对话框的宽度将为 95%(纵向模式)或 65%(横向)。作者问的有点多,但它可能对某人有用。

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

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

                                  【讨论】:

                                  • 什么是ThemeHelper?我的项目中没有此类可用。
                                  • ThemeHelper 只是满足我需要的辅助类。它的方法isPortrait(Context) 返回设备的屏幕方向是纵向还是横向。
                                  • 如果一旦加载对话框然后我们改变方向,这将有问题,它将在 onCreate 中保持其初始设置
                                  【解决方案28】:

                                  像其他人建议的那样,在对话框窗口上指定 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);
                                  

                                  一般来说,在大多数情况下只调整宽度就足够了。

                                  【讨论】:

                                  • 这似乎在 4.0 及更高版本上无法完全运行。它不会填满屏幕的 90%。知道为什么吗?我正在使用 4.0 的摩托罗拉 Xoom 上执行此操作
                                  • @RyanGray 它在具有更新操作系统的三星 Nexus S 上为我工作。如果没有其他信息,很遗憾我无法为您提供帮助。
                                  【解决方案29】:

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

                                  所以,做这样的事情:

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

                                  【讨论】:

                                  • 不为我设置尺寸。 API >= 21。
                                  【解决方案30】:
                                  dialog.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
                                  

                                  【讨论】:

                                  • 这对我有用,并且很容易翻译成 MonoDroid,它的工作原理是这样的(其中 d 是一个新对话框):d.Window.SetLayout(WindowManagerLayoutParams.FillParent, WindowManagerLayoutParams.FillParent);
                                  • 但是 90% 不等于 100%。 FILL_PARENT 表示填充整个宽度,100%,而不是 90%。对吗?
                                  • @Ted 你是对的。您可以将FILL_PARENT 替换为计算为当前显示宽度的 90% 的宽度。但我喜欢这个答案,因为它比其他答案更容易。
                                  猜你喜欢
                                  • 2022-07-18
                                  • 2017-04-08
                                  • 2013-09-09
                                  • 2022-01-22
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  相关资源
                                  最近更新 更多