Center message in android dialog box

Solution 1:

Of course, you can always set the gravity of the original text view. This allows you to not have to worry about formatting and padding.

For example

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");
builder.setMessage("Message");
builder.setPositiveButton("OK", null);
AlertDialog dialog = builder.show();

// Must call show() prior to fetching text view
TextView messageView = (TextView)dialog.findViewById(android.R.id.message);
messageView.setGravity(Gravity.CENTER);

Solution 2:

Create your own TextView object and then supply it to popup builder as View:

AlertDialog.Builder popupBuilder = new AlertDialog.Builder(this);
TextView myMsg = new TextView(this);
myMsg.setText("Central");
myMsg.setGravity(Gravity.CENTER_HORIZONTAL);
popupBuilder.setView(myMsg);

You can control all other text parameters (style, color, size ...). To control margins you may programatically create LinearLayout, set LayoutParams, and then put TextView into it.

Solution 3:

Building off of Chase's answer, here's how to also center the title. I think this is the easiest way. Why android doesn't center by default or make it a simple constructor param is beyond me.

AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("My Title");
builder.setMessage("My message");
builder.setPositiveButton("OK", listener);
AlertDialog dialog = builder.show();

// Must call show() prior to fetching views
TextView messageView = (TextView)dialog.findViewById(android.R.id.message);
messageView.setGravity(Gravity.CENTER);

TextView titleView = (TextView)dialog.findViewById(context.getResources().getIdentifier("alertTitle", "id", "android"));
if (titleView != null) {
    titleView.setGravity(Gravity.CENTER);
}

Solution 4:

we can use as like.

public static void showAlert(Activity activity, String message) {
  TextView title = new TextView(activity);

  title.setText("Your Title Here");
  title.setPadding(10, 10, 10, 10);
  title.setGravity(Gravity.CENTER);
  title.setTextColor(Color.WHITE);
  title.setTextSize(20);

  AlertDialog.Builder builder = new AlertDialog.Builder(activity);
  builder.setCustomTitle(title);
  builder.setMessage(message);
  builder.setCancelable(false);
  builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
      dialog.cancel();
    }
  });

  AlertDialog alert = builder.show();
  TextView messageText = (TextView)alert.findViewById(android.R.id.message);
  messageText.setGravity(Gravity.CENTER);
  messageText.setTextColor(Color.RED);
}