align AlertDialog buttons to center

2019-02-16 05:53发布

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.

8条回答
smile是对你的礼貌
2楼-- · 2019-02-16 06:09

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.

查看更多
3楼-- · 2019-02-16 06:13

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

查看更多
登录 后发表回答