align AlertDialog buttons to center

46.7k views Asked by At

I use this codes for Android (Java) programming:

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

My problem is how make center the button? As you see I try to align button to cnenter using Gravity.CENTER_HORIZONTAL (also .CENTER) but nothing changes. The button is almost in right position.

10

There are 10 answers

2
quad On BEST ANSWER

This worked for me :

    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);
0
Velmurugan V On

Useandroid.support.v7.app.AlertDialog which will align your positive and negative buttons in center.

android.app.AlertDialog will place the button in the top leaving 16dp space in bottom.

0
DevD'Silva On

You can set the positive, negative and neutral buttons, hide both the positive and neutral buttons, and put the negative button where the neutral button is supposed to be(center) by using LayoutParams.

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

in 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());
2
Lucas YU On

Here is something really work.

The parent of the 3 buttons (neutral, positive ve and negative) is ButtonBarLayout, which extends LinearLayout. To centralize a view in LinearLayout, weight, width and layout_gravity(but not gravity) is important, and these code works perfectly:

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);
0
hpereira On

I presume you are using the AlertDialog from the Support library.

If that's the case try replacing your import to android.app.AlertDialog.

3
frank On

Tried crtn's method and Scott Brown's modification, both didn't render how I liked.

crtn's solution didn't change the appearance of the buttons for me at all (I'm using android.R.style.Theme_Material_Light_Dialog) and Scott Brown's solution made my positive button extend past the edge of the dialog parent.

For Theme_Material_Light_Dialog the buttons are contained within a LinearLayout subclass that uses a blank View as its 2nd (index 1) element to push the buttons right.

I grab the Button ref like crtn does:

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

But then I set the leftSpacer to View.GONE and the parent's gravity to CENTER_HORIZONTAL

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

This has the advantage that it doesn't break the dialog's button stacking behavior. The disadvantage is that if the internal layout changes, it will break, so YMMV.

1
Janindu Pathirana On
       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),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ))
                  ],
                ),
              );
          
            },
          ),
0
Edward van Raak On

Ended up with this extension for 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
}

And use with:

.show().withCenteredButtons()
2
Scott Brown On

Use crtn's method, but instead of changing the LayoutParam's gravity, change its width to ViewGroup.LayoutParams.MATCH_PARENT;

0
Ali_Ai_Dev On

If you want to have Positive And Negative Buttons at the same time (Large & Center), you can use something like this:

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