【问题标题】:align AlertDialog buttons to center将 AlertDialog 按钮对齐到中心
【发布时间】:2015-08-24 22:05:02
【问题描述】:

我将此代码用于 Android (Java) 编程:

public static MessageBoxResult showOk(
        Context context, String title, String message, String okMessage)
{
    okDialogResult = MessageBoxResult.Closed;

    // make a handler that throws a runtime exception when a message is received
    final Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message mesg)
        {
            throw new RuntimeException();
        }
    };

    AlertDialog.Builder alert = new AlertDialog.Builder(context);
    alert.setTitle(title);
    alert.setMessage(message);

    alert.setPositiveButton(okMessage, new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int whichButton) {
            okDialogResult = MessageBoxResult.Positive;
            handler.sendMessage(handler.obtainMessage());
        }
    });

    AlertDialog dialog = alert.show();


    // align button to center
    Button b = (Button) dialog.findViewById(android.R.id.button1);
    b.setGravity(Gravity.CENTER_HORIZONTAL);

    // loop till a runtime exception is triggered.
    try { Looper.loop(); }
    catch(RuntimeException e2) {}

    return okDialogResult;
}

我的问题是如何使按钮居中?如您所见,我尝试使用Gravity.CENTER_HORIZONTAL(也为.CENTER)将按钮与中心对齐,但没有任何变化。按钮几乎处于正确位置。

【问题讨论】:

    标签: android button alignment android-alertdialog


    【解决方案1】:

    我假设您正在使用支持库中的 AlertDialog。

    如果是这种情况,请尝试将您的导入替换为 android.app.AlertDialog。

    【讨论】:

      【解决方案2】:

      这对我有用:

          final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AppCompatAlertDialogStyle);
          builder.setCancelable(true);
          builder.setTitle(title);
          builder.setMessage(message);
      
          builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
      
              }
          });
      
      
          final AlertDialog dialog = builder.create();
          dialog.show(); //show() should be called before dialog.getButton().
      
      
          final Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
          LinearLayout.LayoutParams positiveButtonLL = (LinearLayout.LayoutParams) positiveButton.getLayoutParams();
          positiveButtonLL.gravity = Gravity.CENTER;
          positiveButton.setLayoutParams(positiveButtonLL);
      

      【讨论】:

      • 什么是参考positiveBtn
      • 不适用于 Android 7.1.1,但@Scott Brown 下面的解决方案可以正常工作。
      【解决方案3】:

      使用crtn的方法,但是不是改变LayoutParam's的重力,而是把它的宽度改为ViewGroup.LayoutParams.MATCH_PARENT;

      【讨论】:

      • 工作正常。要对像我这样的懒人说清楚:将 行替换为
      • @JohanLund 如果我们有左、中、右等 3 个按钮,我该如何设置?
      【解决方案4】:

      使用android.support.v7.app.AlertDialog 将您的正负按钮居中对齐。

      android.app.AlertDialog 会将按钮放在顶部,在底部留出 16dp 的空间。

      【讨论】:

        【解决方案5】:

        试过crtn的方法和Scott Brown的修改,都没有呈现出我喜欢的样子。

        crtn 的解决方案根本没有为我改变按钮的外观(我使用的是android.R.style.Theme_Material_Light_Dialog),而 Scott Brown 的解决方案使我的正按钮延伸到对话框父级的边缘之外。

        对于Theme_Material_Light_Dialog,按钮包含在LinearLayout 子类中,该子类使用空白视图作为其第二个(索引1)元素来向右推动按钮。

        我像 crtn 一样抓住Button ref:

        AlertDialog dialog = bld.create();
        dialog.show(); //show() MUST be called before dialog.getButton
        Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
        

        然后我将 leftSpacer 设置为 View.GONE 并将父级的重力设置为 CENTER_HORIZONTAL

        LinearLayout parent = (LinearLayout) positiveButton.getParent();
        parent.setGravity(Gravity.CENTER_HORIZONTAL);
        View leftSpacer = parent.getChildAt(1);
        leftSpacer.setVisibility(View.GONE);
        

        这样做的好处是不会破坏对话框的按钮堆叠行为。缺点是如果内部布局改变了就会坏掉,所以YMMV。

        【讨论】:

        • 它有效,我找到的最佳解决方案非常感谢!
        • 我遇到了与 op 相同的问题,将按钮重心更改为中心对我不起作用。您的解决方案效果很好,谢谢。
        • 这个解决方案效果最好,接受的解决方案对我没有帮助,而且 scottbrowns 解决方案对我不起作用,因为它只是匹配父项,因为我想将它左对齐而不是居中。
        【解决方案6】:

        如果你想同时拥有正面和负面按钮(大和中心),你可以使用这样的东西:

        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle("Title");
        alertDialog.setMessage("Message");
        
        alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Yes",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        
        alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "No",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                         dialog.dismiss();
                    }
                 });
        alertDialog.show();
        
        Button btnPositive = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
        Button btnNegative = alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
        
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) btnPositive.getLayoutParams();
        layoutParams.weight = 10;
        btnPositive.setLayoutParams(layoutParams);
        btnNegative.setLayoutParams(layoutParams);
        

        【讨论】:

          【解决方案7】:

          您可以使用 LayoutParams 设置正面、负面和中性按钮,隐藏正面和中性按钮,并将负面按钮放在中性按钮应该位于的位置(中心)。

          在 onCreateView 中:

          dialog = builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
          
                      }
                  })
                           .setPositiveButton(R.string.go_on, new DialogInterface.OnClickListener() {
                               @Override
                               public void onClick(DialogInterface dialog, int which) {
          
                               }
                           })
                           .setNeutralButton(R.string.do_nothing, new DialogInterface.OnClickListener() {
                               @Override
                               public void onClick(DialogInterface dialog, int which) {
          
                               }
                           })
                           .create();
          

          在 onStart() 中:

           super.onStart();
          
              final Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
             positiveButton.setVisibility(View.INVISIBLE);
             final Button neutralButton = dialog.getButton(AlertDialog.BUTTON_NEUTRAL);
             neutralButton.setVisibility(View.INVISIBLE);
             final Button negativeButton = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
             negativeButton.setLayoutParams(neutralButton.getLayoutParams());
          

          【讨论】:

            【解决方案8】:

            这是真正有用的东西。

            3 个按钮(中性、正 ve 和负)的父级是 ButtonBarLayout,它扩展了 LinearLayout。要在 LinearLayout 中集中视图,权重、宽度和 layout_gravity(但不是重力)很重要,这些代码可以完美运行:

            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); //create a new one
            layoutParams.weight = 1.0 f;
            layoutParams.gravity = Gravity.CENTER; //this is layout_gravity
            alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setLayoutParams(layoutParams);
            

            【讨论】:

            • 有效。 @frank 的解决方案也有效。但我更喜欢这个。
            • 澄清一下,确保在#getButton(AlertDialog.[BUTTON_YOU_WANT]) 中传递您希望显示的按钮,并确保在调用alertDialog.show() 后设置layoutParams跨度>
            【解决方案9】:

            最终得到了这个 Kotlin 扩展:

            fun AlertDialog.withCenteredButtons() {
                val positive = getButton(AlertDialog.BUTTON_POSITIVE)
                val negative = getButton(AlertDialog.BUTTON_NEGATIVE)
            
                //Disable the material spacer view in case there is one
                val parent = positive.parent as? LinearLayout
                parent?.gravity = Gravity.CENTER_HORIZONTAL
                val leftSpacer = parent?.getChildAt(1)
                leftSpacer?.visibility = View.GONE
            
                //Force the default buttons to center
                val layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                )
            
                layoutParams.weight = 1f
                layoutParams.gravity = Gravity.CENTER
            
                positive.layoutParams = layoutParams
                negative.layoutParams = layoutParams
            }
            

            并用于:

            .show().withCenteredButtons()
            

            【讨论】:

              【解决方案10】:
                     IconButton(
                          icon: Icon(
                      Icons.logout,
                      color: Colors.black,
                      size: 40,
                    ),
                          onTap: () {
                            return showDialog<String>(
                              context: context,
                              builder: (BuildContext context) => AlertDialog(
                                backgroundColor: Colors.white,
                                title: Text(
                                  'Are you sure you want to logout',
                                  textAlign: TextAlign.center,
                                  style: TextStyle(color: Colors.black),
                                ),
                                actions: <Widget>[
                                  Container(
                                      child: Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      ///yes
                                      TextButton(
                                        onPressed: () =>
                                            Navigator.pushNamedAndRemoveUntil(context,
                                                SecondScreen.id, (route) => false),
                                        child: Container(
                                          padding: EdgeInsets.all(10),
                                          width: 70,
                                          decoration: BoxDecoration(
                                              borderRadius: BorderRadius.circular(10),
                                              color: mainColor),
                                          child: Center(
                                            child: Text(
                                              'Yes',
                                              style: TextStyle(color: Colors.white),
                                            ),
                                          ),
                                        ),
                                      ),
              
                                      ///no
                                      TextButton(
                                        onPressed: () => Navigator.pop(context),
                                        child: Container(
                                          padding: EdgeInsets.all(10),
                                          width: 70,
                                          decoration: BoxDecoration(
                                              borderRadius: BorderRadius.circular(10),
                                              color: Colors.white,
                                              border: Border.all(color: mainColor)),
                                          child: Center(
                                            child: Text(
                                              'No',
                                              style: TextStyle(color: mainColor),
                                            ),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ))
                                ],
                              ),
                            );
                        
                          },
                        ),
              

              【讨论】:

              • 您应该在答案中添加更多详细信息,而不仅仅是发布代码 sn-p。
              猜你喜欢
              • 2021-10-24
              • 1970-01-01
              • 2019-07-04
              • 2021-12-02
              • 1970-01-01
              • 1970-01-01
              • 2015-05-16
              • 1970-01-01
              • 2014-07-19
              相关资源
              最近更新 更多