align AlertDialog buttons to center

40,447

Solution 1

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

Solution 2

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

Solution 3

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

Solution 4

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

Solution 5

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.

Share:
40,447
Babak.Abad
Author by

Babak.Abad

A dedicated AI programmer with a focus on machine vision applications I develop apps and optimize tasks with help of machine learning. I can learn machines and optimize them to do tasks such as reading texts, classifying objects, recognizing voice, or even read emotions from biosignals. As a CTO, I manage my team to develop artificial intelligence (AI) solutions. I determine solution requirements including, computers, cameras, bandwidth, etc. As a programmer, I can develop machine learning apps using multiple programming languages. My current objectives include developing speed enforcement cameras. My experience includes developing real-time automatic license plate recognition (ALPR) system. I developed a license plate detector, OCR pipeline, and camera synchronizer (an electronic board). I also developed an RFID-tag-based system as a customer management system. artificial intelligence | machine learning | machine vision | deep learning | intelligent transportation | OCR | C# | Python | Matlab

Updated on August 03, 2021

Comments

  • Babak.Abad
    Babak.Abad almost 3 years

    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.