将 AlertDialog 按钮对齐到中心 [英] align AlertDialog buttons to center

查看:58
本文介绍了将 AlertDialog 按钮对齐到中心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将此代码用于 Android (Java) 编程:

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

我的问题是如何使按钮居中?如您所见,我尝试使用 Gravity.CENTER_HORIZONTAL(还有 .CENTER)将按钮与 cnenter 对齐,但没有任何变化.按钮几乎在正确的位置.

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.

推荐答案

这对我有用:

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

这篇关于将 AlertDialog 按钮对齐到中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆