简体   繁体   中英

How to center text in Alert Dialog Builder?

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

        }

This piece of code does the job by default, without providing your own custom view to the 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();

不要设置消息,而是使用带有居中文本的View AlertDialog.Builder.setView(View)

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

You can try this simple method:

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

For Material Alert Dialog would be like this:

MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(this, com.google.android.material.R.style.ThemeOverlay_Material3_MaterialAlertDialog_Centered)
    .setTitle("Titulo")
    .setIcon(R.drawable.people)
    .setMessage("un mensaje cualquiera");
AlertDialog dialog = builder.show();    
((TextView) dialog.findViewById(android.R.id.message)).setGravity(Gravity.CENTER);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM