将AlertDialog按钮对齐到中心

时间:2015-06-09 21:20:40

标签: android button alignment android-alertdialog

我将此代码用于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)将按钮与cnenter对齐,但没有任何变化。按钮几乎处于正确的位置。

10 个答案:

答案 0 :(得分:29)

使用crtn的方法,但不要更改LayoutParam's重力,而是将其宽度更改为ViewGroup.LayoutParams.MATCH_PARENT;

答案 1 :(得分:11)

这对我有用:

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

答案 2 :(得分:10)

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

Dialog Positive & Negative Buttons

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

答案 3 :(得分:4)

这确实有用。

三个按钮(中性,正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);

答案 4 :(得分:3)

尝试了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。

答案 5 :(得分:1)

我认为您正在使用支持库中的AlertDialog。

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

答案 6 :(得分:0)

使用android.support.v7.app.AlertDialog将正面和负面按钮对齐。

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

答案 7 :(得分:0)

您可以设置正,负和中性按钮,隐藏正按钮和中性按钮,并使用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 :(得分:0)

最终获得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()

答案 9 :(得分:-2)

       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),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ))
                  ],
                ),
              );
          
            },
          ),