Java 如何在警报对话框生成器中居中文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21123653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:45:40  来源:igfitidea点击:

How to center text in Alert Dialog Builder?

javaandroidandroid-alertdialog

提问by Violin Nz

I'm trying to center some text in a default Alert Dialog Builder Here's my code so far, but it defaults to the left.

我正在尝试在默认警报对话框生成器中居中一些文本 这是我目前的代码,但它默认在左侧。

            new AlertDialog.Builder(getActivity())
                    .setTitle("Well done!")
                    .setMessage("Message centered????")

                    .setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    // TODO Auto-generated method stub

                                }
                            })

                    .setIcon(R.drawable.img_ok)
                    .show();

        }

采纳答案by Gil Vegliach

Instead of setting the message, use AlertDialog.Builder.setView(View)with a Viewwith centred text

相反,设置消息的,使用AlertDialog.Builder.setView(View)View与居中的文本

回答by AlexAndro

This piece of code does the job by default, without providing your own custom view to the AlertDialog.Builder.

这段代码默认完成这项工作,无需向AlertDialog.Builder.

  AlertDialog dialog = builder.show(); //builder is your just created builder
    TextView messageText = (TextView)dialog.findViewById(android.R.id.message);
    messageText.setGravity(Gravity.CENTER);
    dialog.show();

回答by Angga Dwi Prasetya

you can try this code

你可以试试这个代码

public void Info(){
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Info Aplikasi");
    builder.setIcon(R.drawable.info_adp);
    builder.setMessage("Jakarta Hospital");
    builder.setCancelable(false);
    builder.setPositiveButton("Exit", null);
    AlertDialog dialog = builder.show();
    TextView messageView = (TextView)dialog.findViewById(android.R.id.message);
    messageView.setGravity(Gravity.CENTER);
}

回答by Farido mastr

You can try this simple method:

你可以试试这个简单的方法:

textView.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
textView.setGravity(Gravity.CENTER);
alert.setView(textView);