android - 将 AlertDialog 按钮对齐到中心

标签 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)将按钮与中心对齐,但没有任何变化。按钮几乎处于正确位置。

最佳答案

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

关于android - 将 AlertDialog 按钮对齐到中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30743038/

相关文章:

jQuery移动按钮默认旋转90°并添加到网格

CSS/HTML 定位 - 元素叠加内容

objective-c - Objective-C : Programmatically create a UIImageView

html - css 如何将绝对定位的子元素对齐到流体宽度父元素的右侧

html - 将 div 彼此对齐

Network mound 下的 Android Studio -

android - ViewStub 必须有一个非空的 ViewGroup viewParent

android - 通过将 Canvas 视为 View 来绘制矩形

android - Android 中的新 Activity "enter from the side"

c# - 当 NumericUpDown 控件中的值大于某个数字时,如何禁用按钮?